如何使用Zend\Form将类应用于标签并在呈现的表单中添加行结尾?

sha*_*zen 0 zend-framework2 zend-form2

我已经按照Zend Framework 2的教程进行了操作,我在渲染表单上看到,绑定标签的约定是将input元素包装在label标签中,而不是使用'for'属性.虽然本教程没有涵盖它,但我(正确地)推断出属性数组允许在输入元素本身上设置类,但我真正想要做的是将类应用于选项下定义的标签.

这是教程中使用的示例(来自AlbumForm.php):

$this->add(array(
    'name'       => 'title',
    'attributes' => array(
        'class' => 'required', // <- I added this
        'type' => 'text',
    ),
    'options' => array(
        'label' => 'Title',
    ),
));
Run Code Online (Sandbox Code Playgroud)

这将呈现如下:

<label><span>Title</span><input name="title" class="required" type="text" value=""></label>
Run Code Online (Sandbox Code Playgroud)

或者,我可以将类应用于span标记,但我更喜欢在标签上使用类,然后使用css子选择器作为span和input元素

我重新阅读了教程以及相应部分的注释,甚至深入研究了Zend\Form API文档本身,我没有看到如何以这种方式声明表单元素时将类属性应用于标签.


另一个带有表单渲染的小挑剔是它看起来是内联呈现的,表单元素之间没有换行符.我通过在视图脚本(add.phtmledit.phtml)中添加换行符来解决这个问题,如下所示:

echo $this->formRow($form->get('title')) . "\n";
Run Code Online (Sandbox Code Playgroud)

但是,对于视图中的每个回显表单语句而言,这似乎很痛苦,并且formCollection()还使用内联呈现整个表单输出.出于易读性的目的,我希望在查看源代码时至少有适当的换行符(我也希望适当的缩进,但这似乎是一个很高的顺序,因为即使IDE在大多数情况下都会出错)

那么,我是否缺少这些问题的内置选项,或者是一种定义工厂或帮助器的方法?如果我需要编写帮助程序,我希望它适用于所有模块.

Rob*_*len 6

要在标签中添加类,请在配置中使用"label_attributes"键:

$this->add(array(
    'name'       => 'title',
    'attributes' => array(
        'type' => 'text',
    ),
    'options' => array(
        'label' => 'Title',
        'label_attributes' => array(
            'class' => 'required',
        ),
    ),
));
Run Code Online (Sandbox Code Playgroud)

要添加新行,您可以编写自己的FormRow视图助手,也可以在视图脚本中单独渲染标签和元素,如下所示:

$form = $this->form;
$form->prepare();
echo $this->form()->openTag($form) . "\n";

echo $this->formLabel($form->get('title')) . "\n";
echo $this->formInput($form->get('title')) . "\n";
echo $this->formElementErrors($form->get('title'));

// other elements
echo $this->form()->closeTag($form) . "\n";
Run Code Online (Sandbox Code Playgroud)