ZF2中如何在一处配置提交元素

How to configure submit elements in one place in ZF2

我使用类似于 skeleton application tutorial:

的数组符号为我的 ZF2 表单创建提交按钮
     $this->add(array(
         'name' => 'submit',
         'type' => 'Submit',
         'attributes' => array(
             'value' => 'Go',
             'id' => 'submitbutton',
         ),
     ));

如果我将我的项目从专辑列表扩展到书籍列表、DVD 列表、宠物列表、YuGiOhCards 列表等;每个新模块都需要自己的形式。重写相同的代码以向每个表单添加提交按钮非常容易;但为了确保一致性,在单个位置编写一次提交按钮并从每个表单 类.

调用它是有意义的

如果我想重复使用 "global" 提交按钮,我应该在哪里编写代码以及如何调用它?

您可以使用表单元素管理器;这是一个专门的表单元素服务管理器,提供所有常用的可重用服务和使用工厂的 DI。

例如,您可以将按钮作为服务提供。

'form_elements' => [
    'factories' => [
        'MySubmitButton' => 'MyModule\Form\Element\MySubmitButtonFactory',
    ],
],

然后创建工厂。

namespace MyModule\Form\Element;

use Zend\Form\Element\Submit; 

class MySubmitButtonFactory
{
    public function __invoke($formElementManager, $name, $requestedName)
    {
        $element = new Submit('submit');
        $element->setAttributes([
            'value' => 'Go',
            'id' => 'submitbutton'
        ]);
        return $element;
    }
}

当您需要将此添加到表单时,您应该首先从 FormElementManager 服务中获取元素。

$formElementManager = $serviceManager->get('FormElementManager');
$button = $formElementManager->get('MySubmitButton');

或者当您需要通过配置在表单中添加时,表单工厂将使用 type 键并为您从 FormElementManager 中拉取。

 $this->add([
     'name' => 'submit',
     'type' => 'MySubmitButton',
 ]);

您可以使用 traits.

只需创建将包含 addSubmit() 方法的特征

protected function addSubmit()
{
    $this->add([
        'name' => 'submit',
        'type' => 'Submit',
        'attributes' => [
            'value' => 'Go',
            'id' => 'submitbutton',
        ],
    ]);
}

并在您的表单中使用它。

class MyForm extends Form
{
    use SubmitButtonFormTrait;

    // ...

    public function __construct($name = null)
    {
        parent::__construct('customName');

        // ...

        $this->addSubmit();
    }
}