以Zend形式渲染无线电元素

时间:2013-09-05 06:33:34

标签: php html forms zend-framework zend-framework2

我使用Zend\Form定义了一个表单。在那里,有一个单选按钮。

    $this->add(array(
        'name' => 'nationality_radio',
        'type' => 'Radio',
        'options' => array(
            'value_options' => array(
                'local' => 'Local',
                'expatriate' => 'Expatriate',
            ),
        )
    ));

其值不与数据库列直接绑定。但它应该填充从DB获取的正确值并保存用户输入。 (例如 - 如果表格列nationality的值为local,则应在单选按钮中选择local

渲染时应显示为..

enter image description here

在表单加载时,它会考虑列nationality的选择选项。它将包含localexpatriate

的值
        <?php
        if ($candidate->nationality == 'local'){
            $local = 'checked';
        } else if ($candidate->nationality == 'local'){
            $expatriate = 'checked';
        }
        ?>

在纯HTML中,我可以按照以下方式执行,

    <div class="profile_item list-group-item">
        <span class="item_title">Local: </span>
        <span class="item_content"><input type="radio" name="nationality" value="local" <?php echo $local ?>></span><br>
        <span class="item_title">Expatriate: </span>
        <span class="item_content"><input type="radio" name="nationality" value="expatriate" <?php echo $expatriate ?>></span>
    </div>

但是由于Zend表单使用<?php echo $this->formRow($form->get('nationality_radio')); ?>呈现,我无法做到。它只显示如下。

enter image description here

我如何达到我的要求?

2 个答案:

答案 0 :(得分:1)

用于在控制器方法中设置值:

$form = new YourFormClass();
//are you using fieldsets? let's say no...
//if accepted value for $candidate->nationality could be only 'local' and 'expatriate',
//check the scope with your defined value_options or use an if
$form->get('nationality_radio')->setValue($candidate->nationality);

在您的观点中使用formRadio帮助:

<?php echo $this->formRadio($form->get('nationality_radio'),\Zend\Form\View\Helper\FormRadio::LABEL_PREPEND);?>

查看文档:{​​{3}}

或检查课程:

\Zend\Form\View\Helper\FormRadio

\Zend\Form\View\Helper\FormMultiCheckbox

$labelPosition的可接受值为:

const LABEL_APPEND  = 'append';
const LABEL_PREPEND = 'prepend';

答案 1 :(得分:0)

试试这个

 <?php
            if ($candidate->nationality == 'local'){
                $LocalChecked="checked";
            } 
           else {
                $expatriateChecked ="checked";
            }
     ?> 



<div class="profile_item list-group-item">
        <span class="item_title">Local: </span>
        <span class="item_content"><input type="radio" name="nationality" value="local" <?php echo $LocalChecked ?>></span><br>
        <span class="item_title">Expatriate: </span>
        <span class="item_content"><input type="radio" name="nationality" value="expatriate" <?php echo $expatriateChecked ?>></span>
    </div>