ZF2 - Register custom form element

2019-09-09 02:35发布

问题:

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