呈现Zend Forms中单选元素中的单个选项


render individual option from radio Element in Zend Forms

我在Zend表单中有这个元素

$genderOptions = array( 'male'=>'male', 'Female'=>'Female');
$gender= new Zend_Form_Element_Radio('gender');
$gender->setDecorators(array('ViewHelper'))
       ->setAttrib('name', 'gender')
       ->setAttrib('class', 'required error pull-right')
       ->setAttrib('id', 'gender')
       ->setRequired(false)
       ->setMultiOptions($genderOptions);

我想在viewscript(phtml文件)中单独检索输入。我试过了作为

 <div>
 <span>Male</span>
    echo $this->myForm->gender['male'];
 </div>

<div>
<span>Female</span>
 echo   $this->myForm->gender['female'];
</div>

如何使用Zend Form来完成此操作?

感谢

对于扩展Zend_Form_Element_Multi的表单元素,可以使用getMultiOption($option)获取单个选项。

查看.phtml

<div>
  <span>Male</span>
  <?php echo $this->myForm->gender->getMultiOption('male'); ?>
</div>
<div>
  <span>Female</span>
  <?php echo $this->myForm->gender->getMultiOption('female'); ?>
</div>

或者,在尝试使用之前,您可能需要检查该选项是否可用(或者您将获得NULL

<?php
  $gender = $this->myForm->gender;
  $option = $gender->getMultiOptions(); // returns assoc array
  if (isset($option['male'])) 
    printf('<div><span>Male</span>%s</div>', $option['male']);
  if (isset($option['female'])) 
    printf('<div><span>Female</span>%s</div>', $option['female']);
?>

编辑

重读你的问题后,我可以看出你在寻找单独的无线电元素,而不是价值。

这可能更难实现,因为Zend_Form_Element_Radio类实际上代表所有无线电选项;其中,视图助手Zend_View_Helper_FormRadio在每个"选项"(即男性、女性)上循环,并返回包含每个<input type="radio"/>的完整HTML字符串。

令人震惊的是,Zend_View_Helper_FormRadio助手实际上在一个方法中包含了所有HTML生成代码;这使得很难在不重复的情况下覆盖它。

就我个人而言,我会:

  • 创建一个扩展Zend_View_Helper_FormElement的新助手MyNamespace_View_Helper_CustomFormRadio
  • Zend_View_Helper_FormRadioFormRadio())的全部内容复制到您的新助手中
  • 修改创建每个无线电input的部分

例如

 $radio = '<div><span'
  . $this->_htmlAttribs($label_attribs) . '>'
  . (('prepend' == $labelPlacement) ? $opt_label : '')
  . '<input type="' . $this->_inputType . '"'
  . ' name="' . $name . '"'
  . ' id="' . $optId . '"'
  . ' value="' . $this->view->escape($opt_value) . '"'
  . $checked
  . $disabled
  . $this->_htmlAttribs($attribs)
  . $this->getClosingBracket()
  . (('append' == $labelPlacement) ? $opt_label : '')
  . '</span></div>';
  • 然后您可以在视图中使用$this->customFormRadio()