【问题标题】:How to set class for the radio buttons set's container in a ZF2 Form?如何在 ZF2 表单中为单选按钮集的容器设置类?
【发布时间】:2017-03-14 14:25:35
【问题描述】:

在我的表单中,我有一个单选按钮集 foo,定义如下:

$this->add(
    [
        'type' => 'radio',
        'name' => 'foo',
        'options' => [
            'label' => 'foo',
            'value_options' => [
                [
                    'value' => Foo::BAR,
                    'label' => 'bar'
                ],
                [
                    'value' => Foo::BUZ,
                    'label' => 'buz'
                ]
            ],
            'label_attributes' => [
                'class' => 'col-md-12',
            ]
        ],
        'attributes' => [
            'class' => 'field-foo'
        ]
    ]);

在视图脚本中它是这样调用的:

$this->formRow($myFieldset->get('foo'));

所以我得到了这个 HTML:

<fieldset>
    <legend>foo</legend>
    <label class="col-md-12">
        <input type="radio" value="bar" class="field-foo" name="my_fieldset[foo]">bar
    </label>
    <label class="col-md-12">
        <input type="radio" value="buz" class="field-foo" name="my_fieldset[foo]">buz
    </label>
</fieldset>

现在我想将此单选按钮集标记为必需。对于input[type="text"] 字段,我通过label 进行管理:

label.required:before {
    content: '* ';
    color: #ff0000;
}

在这种情况下,我需要访问legend 或至少fieldset,以便定义

fieldset > legend.required:before, /*or*/
fieldset.required > legend:before {
    content: '* ';
    color: #ff0000;
}

如何做到这一点?如何为 Zend Framework 2 中设置的单选按钮的fieldset / legend 元素设置一个类?

【问题讨论】:

    标签: php forms zend-framework2 zend-form zend-form-element


    【解决方案1】:

    我认为您无法通过选项来做到这一点。但是您可以使用部分来模板化您的输入:

    $this->formRow($myFieldset->get('foo'), null, null, 'path/to/partials/some-partial-file.phtml');
    

    在此文件中,您可以自定义呈现输入的方式,添加您需要的内容:

    <?php
    /**
     * @var \Zend\Form\Element\Radio $element
     */
    
    $element_options = $element->getValueOptions();
    $element_attributes = $element->getAttributes();
    $element_value = $element->getValue();
    ?>
    <fieldset>
        <legend><?php echo $element->getLabel(); ?> * </legend>
        <?php foreach($element_options as $key => $value) { ?>
    
        <label class="col-md-12">
            <input type="radio" value="<?php echo $value['value']; ?>" class="field-foo" name="<?php echo $element_attributes['name']; ?>[]"><?php echo $value['value']; ?>
        </label>
        <?php } ?>
    </fieldset>
    

    Zend 传递一个 $element 变量来保存表单输入元素

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 2016-03-24
      • 1970-01-01
      相关资源
      最近更新 更多