How to trigger fieldset factory in ZF3

♀尐吖头ヾ 提交于 2019-12-24 15:26:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!