我可以在Zend Form 1.11中创建名称[]的数组输入字段

时间:2014-06-19 08:20:48

标签: html zend-framework zend-form

如何在Zend Framework 1.11中使用Zend Form

创建这样的输入名称
<input name="name[]" class="name">
<input name="name[]" class="name">
<input name="name[]" class="name">

我不想要数组中的索引/键。我希望它充满活力。

1 个答案:

答案 0 :(得分:1)

您可以尝试制作自己的View_Helper

我可以提出这个建议:

我的库中,创建帮助程序目录 在此目录中,创建一个 FormArray.php 文件,如下所示:(它是Zend_View_Helper_FormText类的改编版)

class Zend_View_Helper_FormArray extends Zend_View_Helper_FormElement
{
    public function formArray($name, $value = null, $attribs = null)
    {
        $info = $this->_getInfo($name, $value, $attribs);
        extract($info); // name, value, attribs, options, listsep, disable

        // build the element
        $disabled = '';
        if ($disable) {
            // disabled
            $disabled = ' disabled="disabled"';
        }
        $sep = '';
        $end = 1;
        if (isset($attribs['nb_repeat']) && is_int($attribs['nb_repeat']) && $attribs['nb_repeat'] >1)
            $end = $attribs['nb_repeat'];

        if (isset($attribs['sep_repeat']))
            $sep = $attribs['sep_repeat'];

        $xhtml = '';
        unset($attribs['nb_repeat']);
        unset($attribs['sep_repeat']);
        for ($i = 1; $i <= $end; $i++){
            if ($i != 1)
                $xhtml .= $sep;
            $xhtml .= '<input name="' . $this->view->escape($name) . '[]"'
                    . ' value="' . $this->view->escape($value) . '"'
                    . $disabled
                    . $this->_htmlAttribs($attribs)
                    . $this->getClosingBracket();
        }
        return $xhtml;
    }
}

正如您所看到的,我添加了2个属性nb_repeatsep_repeat来定义您想要的输入数量以及每个属性的分隔符。
我也删除了id属性。

在您的Controller中,添加此视图助手的路径,如下所示:

$this->view->addHelperPath('My/Helper/', 'My_Helper'); 

现在,在您的表单中,您可以创建这样的元素:

$test = new Zend_Form_Element_Text('name');
$test->setAttrib('class', 'name')
      ->setAttrib('nb_repeat', 3)    // to have 3 input
      ->setAttrib('sep_repeat', "\n") // to have a new line betwwen each input in your code source
      ->addDecorators(array(
                          array('ViewHelper',
                                    array('helper' => 'formArray')
                               ),                                                                                       
                          )                           
                     );

我希望它会对你有所帮助。 :)