如何在标签zend形式中包装单选按钮组

时间:2013-12-28 08:06:40

标签: zend-framework zend-form radio-group

我希望以下html包含zend形式的两个单选按钮组

        <label class="inline">
        <input type="radio" name="form-field-radio">
    <span class="lbl"> Male</span>
    </label>
        &nbsp; &nbsp; &nbsp;
   <label class="inline">
    <input type="radio" name="form-field-radio">
    <span class="lbl"> Female</span>
   </label>

我正在使用以下代码在Zend Form中创建此按钮

$gender = $this->CreateElement('radio','gender')
        ->addFilter(new Zend_Filter_StringTrim())
        ->setMultiOptions(array('M'=>'Male', 'F'=>'Female'))
        ->setDecorators(array( array('ViewHelper') ));

但是我不知道在这段代码中设置lable和span类的位置。

请帮忙。

感谢。

1 个答案:

答案 0 :(得分:0)

我不确定它是否是我第一次使用zend框架时这样做的完美方法,但是如果你觉得有用的话,我仍然会采取以下步骤:

首先,我创建了一个自定义装饰器,它扩展了Zend_Form_Decorator_Abstract并将其保存在'decorator/My_Form_Decorator.php'位置。 decorator是我在root中创建的目录。

.
 /decorator
 /application 

等...

然后我将它包含在控制器中。我已经读过有一些方法可以添加像addPrefixPath()这样的装饰器,但是为了时间的缘故,我只是将装饰器文件包含在'include "../decorator/My_Form_Decorator.php";'的顶部。然后使用CreateElement方法而不是Zend_Form_Element方法。

以下是自定义无线电装饰器的代码

My_Form_Decorator.php

class My_Decorator_RadioInput extends Zend_Form_Decorator_Abstract
{


    public function render($content)
    {
        $element = $this->getElement();

        $label   = htmlentities($element->getLabel());
        $type = $element->type;
        $name = $element->elemName;
        $multiOptions = $element->multiOptions;
        $labelClass = $element->labelClass;
        $spanClass = $element->spanClass;
        $markup='';

        if(!empty($type) && !empty($name) && !empty($multiOptions)  && is_array($multiOptions)){
         foreach($multiOptions as $key=>$value){
           $markup .='<label class="'.$labelClass.'"><input type="radio" name="'.$name.'" value="'.$key.'"> <span class="'.$spanClass.'">'.$value.'</span></label>';                    
         }
        }
        return $markup;
    }
}

这是我的控制器功能中的代码

IndexController.php

$decorator = new My_Decorator_RadioInput();
$form = new Zend_Form();
$form->setAttrib('id', 'test');
$element   = new Zend_Form_Element('foo', array(
    'elemName'=>'gender',
    'type' =>'radio',
    'multiOptions' => array('M'=>'Male', 'F'=>'Female'),
    'labelClass'=>'inline',
    'spanClass'=>'lbl',
    'decorators' => array($decorator),
));
$form->addElement($element);
$this->view->form = $form;

并在视图中查看index.phtml

echo $this->form

希望这对你有帮助..

相关问题