如何在ZF3中触发Fieldset Factory [英] How to trigger fieldset factory in ZF3
问题描述
我需要使用工厂设置字段.我知道如何针对表单进行操作,但如何针对字段集进行操作?
I need to use factory for fieldset. I know how to do it for form, but how to do it for fieldset?
表单代码为:
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对象.但是如何告诉解析器使用自定义字段集工厂创建字段集对象?
As one can see above the line 'type' => Outline::class,
tells parser to create fieldset object. But how to tell parser to create fieldset object with a custom fieldset factory?
推荐答案
FormElementManager
是ServiceManager
的扩展,因此您必须将其配置为与服务管理器相同.这是一个例子
FormElementManager
is extending from ServiceManager
so you have to config it same as service manager. Here's an example
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
相同.您将通过服务管理器调用字段集;
With this config, when you call \Application\Fieldset\Outline::class
, \Application\Fieldset\Factory\OutlineFactory::class
will be triggered by FormElementManager
. Everything same as ServiceManager
. You will call your fieldset as via service manager;
$container->get('FormElementManager')->get(\Application\Fieldset\Outline::class);
您还可以通过getFormFactory
方法在表单/字段集中对其进行调用;
Also you can call it in forms/fieldsets via getFormFactory
method;
function init() { // can be construct method too, nothing wrong
$this->getFormFactory()->getFormElementManager()->get(\Application\Fieldset\Outline::class);
}
当然,您可以在工厂支持的扩展名中使用它的名称.
And of course you can use it's name in your factory-backed form extensions.
但是,如果您通过new
关键字创建它,则不会触发您的工厂.
BUT if you create it via new
keyword, your factory will not be triggered.
这篇关于如何在ZF3中触发Fieldset Factory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!