我需要使用工厂进行字段设置。我知道如何针对表单进行操作,但是如何针对字段集进行操作?
表单代码为:
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对象。但是,如何告诉解析器使用自定义字段集工厂创建字段集对象?
FormElementManager
是从扩展的,ServiceManager
因此您必须将其配置为与服务管理器相同。这是一个例子
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
。一切都一样ServiceManager
。您将通过服务经理呼叫您的字段集;
$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
关键字创建它,则不会触发您的工厂。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句