问题
I need to use factory for fieldset. I know how to do it for form, but how to do it for fieldset?
The form code is:
namespace Application\Form;
use Application\Fieldset\Outline;
use Zend\Form\Element;
use Zend\Form\Form;
class Message extends Form
{
public function __construct()
{
parent::__construct('message');
$this->setAttribute('method', 'post');
$this->add([
'type' => Outline::class,
'options' => [
'use_as_base_fieldset' => true,
],
]);
$this->add([
'name' => 'submit',
'attributes' => [
'type' => 'submit',
'value' => 'Send',
],
]);
}
}
As one can see above the line 'type' => Outline::class,
tells parser to create fieldset object. But how to tell parser to create fieldset object with a custom fieldset factory?
回答1:
FormElementManager
is extending from ServiceManager
so you have to config it same as service manager. Here's an example
class MyModule {
function getConfig(){
return [
/* other configs */
'form_elements' => [ // main config key for FormElementManager
'factories' => [
\Application\Fieldset\Outline::class => \Application\Fieldset\Factory\OutlineFactory::class
]
]
/* other configs */
];
}
}
With this config, when you call \Application\Fieldset\Outline::class
, \Application\Fieldset\Factory\OutlineFactory::class
will be triggered by FormElementManager
. Everything same as ServiceManager
. You will call your fieldset as via service manager;
$container->get('FormElementManager')->get(\Application\Fieldset\Outline::class);
Also you can call it in forms/fieldsets via getFormFactory
method;
function init() { // can be construct method too, nothing wrong
$this->getFormFactory()->getFormElementManager()->get(\Application\Fieldset\Outline::class);
}
And of course you can use it's name in your factory-backed form extensions.
BUT if you create it via new
keyword, your factory will not be triggered.
来源:https://stackoverflow.com/questions/49097075/how-to-trigger-fieldset-factory-in-zf3