ZF2 - Register custom form element

二次信任 提交于 2019-12-12 05:37:31

问题


In ZF2, I've overridden the Text element with my own (call it My\Form\Element\Text). Now I want to make it so that when I add a text element to the form, it defaults to my overridden class and not Zend\Form\Element\Text:

$this->add([
    'type' => 'text',
    'name' => 'to',
]);

I know that I could use 'type' => 'My\Form\Element\Text' instead of just 'type' => 'text', but I'm trying to find out if I can avoid that and just use the custom element by default.

I've tried both of these techniques:

module.config.php

return [
    'form_elements' => [
        'invokables' => [
            'text' => 'My\Form\Element\Text',
        ],
    ],
];

Module.php

class Module {

    public function getFormElementConfig() {
        return [
            'invokables' => [
                'text' => 'My\Form\Element\Text',
            ],
        ];
    }
}

Neither of these worked (still getting an instance of Zend\Form\Element\Text). Is there some other way of registering the element so that the Zend\Form\Factory::create() method creates an instance of my custom element instead of the Zend version?


回答1:


Although your config is correct, there are a couple of gotchas to be aware of when using custom elements, detailed in the docs here

Catch 1

If you are creating your form class by extending Zend\Form\Form, you must not add the custom element in the __construct-or, but rather in the init() method

Catch 2

You must not directly instantiate your form class, but rather get an instance of it through the Zend\Form\FormElementManager



来源:https://stackoverflow.com/questions/19405263/zf2-register-custom-form-element

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