ZF2 - 注册自定义表单元素 [英] ZF2 - Register custom form element
问题描述
在 ZF2 中,我用我自己的元素覆盖了 Text 元素(称为 My\Form\Element\Text
).现在我想这样做,当我向表单添加文本元素时,它默认为我覆盖的类而不是 Zend\Form\Element\Text
:
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',
]);
我知道我可以使用 'type' =>'My\Form\Element\Text'
而不是 'type' =>'text'
,但我想知道是否可以避免这种情况,并且默认情况下只使用自定义元素.
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',
],
];
}
}
这些都不奏效(仍然得到一个 Zend\Form\Element\Text
的实例).是否有其他注册元素的方法,以便 Zend\Form\Factory::create()
方法创建我的自定义元素的实例而不是 Zend 版本?
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?
推荐答案
尽管您的配置是正确的,但在使用自定义元素时仍有一些问题需要注意,在此处的文档中有详细说明
Although your config is correct, there are a couple of gotchas to be aware of when using custom elements, detailed in the docs here
抓住 1
如果您通过扩展 Zend\Form\Form 创建表单类,则不能在 __construct-or 中添加自定义元素,而应在 init() 方法中添加
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
抓住 2
你不能直接实例化你的表单类,而是通过 Zend\Form\FormElementManager 获取它的一个实例
You must not directly instantiate your form class, but rather get an instance of it through the Zend\Form\FormElementManager
这篇关于ZF2 - 注册自定义表单元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!