代码之家  ›  专栏  ›  技术社区  ›  trzczy

如何在ZF3中触发fieldset工厂

  •  1
  • trzczy  · 技术社区  · 6 年前

    我需要为fieldset使用factory。我知道如何处理表单,但如何处理字段集?

    表格代码为:

    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',
                ],
            ]);
        }
    }
    

    正如人们在这条线的上方所看到的 'type' => Outline::class, 告诉解析器创建fieldset对象。但如何告诉解析器使用自定义字段集工厂创建字段集对象呢?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Mehmet SÖĞÜNMEZ    6 年前

    FormElementManager 正在扩展自 ServiceManager 因此,您必须将其配置为与service manager相同。这里有一个例子

    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 */
               ];
         }
    }
    

    使用此配置,当您调用 \Application\Fieldset\Outline::class , \Application\Fieldset\Factory\OutlineFactory::class 将由触发 FormElementManager 。一切都一样 服务经理 。您将通过service manager调用您的字段集as;

    $container->get('FormElementManager')->get(\Application\Fieldset\Outline::class);
    

    您还可以通过以下方式在表单/字段集中调用它 getFormFactory 方法

    function init() { // can be construct method too, nothing wrong
       $this->getFormFactory()->getFormElementManager()->get(\Application\Fieldset\Outline::class);
    }
    

    当然,您可以在工厂支持的表单扩展中使用它的名称。

    但是 如果您通过 new 关键字,将不会触发您的工厂。