如何自定义ZF2上单选按钮的HTML输出


How to customize the HTML output of radio buttons on ZF2?

我想在Zend Framework 2上自定义单选按钮的HTML输出。我正在使用Zend'Form'Fieldset

在我的Fieldset类中是这样的:

$this->add(array( 
    'name' => 'type', 
    'type' => 'Zend'Form'Element'Radio', 
    'attributes' => array(
        'value' => $this->getType(),
    ), 
    'options' => array( 
        'label' => 'Type',
        'label_attributes' => array(
            'class' => '',
        ),
        'value_options' => array(
            '1' => 'Option 1',
            '2' => 'Option 2',
            '3' => 'Option 3'
        ),
    ),
));

在我看来:

<div class="row">
    <div class="input-field col s6">
        <?php echo $this->formRadio($form->get('type')) ?>
    </div>
</div>

它是这样打印的:

<div class="row">
    <div class="input-field col s6">
        <label class="radio">
            <input type="radio" name="type" value="1" checked="checked">Option 1
        </label>
        <label class="radio">
            <input type="radio" name="type" value="2">Option 2
        </label>
        <label class="radio">
            <input type="radio" name="type" value="3">Option 3
        </label>
    </div>
</div>

但我希望它打印如下:

<div class="row">
    <div class="input-field col s6">
        <p>
            <input name="type" type="radio" id="option1" />
            <label for="option1">Option 1</label>
        </p>
        <p>
            <input name="type" type="radio" id="option2" />
            <label for="option2">Option 2</label>
        </p>
        <p>
            <input name="type" type="radio" id="option3" />
            <label for="option3">Option 3</label>
        </p>
    </div>
</div>

我需要改变,因为我的布局使用MaterializeCSS,我认为它只能这样工作。

更新

我的解决方案是:

<div class="row">
    <div class="input-field col s6">
        <?php $element = $form->get('type') ?>
        <?php foreach ($element->getValueOptions() as $value => $label): ?>
            <?php $checked = $value == $element->getValue() ? 'checked="true"' : ''; ?>
            <p>
                <input name="<?php echo $element->getName() ?>" type="radio" id="<?php echo $element->getName().$value ?>" value="<?php echo $value ?>" <?php echo $checked ?>>
                <label for="<?php echo $element->getName().$value ?>"><?php echo $label ?></label>
            </p>
        <?php endforeach ?>
    </div>
</div>

如果您希望对表单元素进行不同的呈现,则应该分别调用它们。

看看http://zf2cheatsheet.com/#form并向下滚动查看帮助程序的列表