Zend表单使用相同的名称,两个字段使用数组表示法


Zend form using same name for two field using array notation

使用Zend Framework 1.9。我有一张表格:

...
    $this->addElement('text', 'field', [
        'label' => 'Name (*)',
        'belongsTo' => 'a'
    ]);
    $this->addElement('text', 'field', [
        'label' => 'Name (*)',
        'belongsTo' => 'b'
    ]);
...

我正在使用数组表示法来生成这样的嵌套数组:

array (size=10)
  'a' => 
    array 
      'field' => string '' (length=0)
  'b' => 
    array 
      'field' => string '' (length=0)

这个符号对我来说很有用,但当我用这样的数组结构填充表单时:

$data=[
       "a"=>
            [
             "field"=>"MY CUSTOM TEXT"
            ],
       "b"=>
            [
             "field"=>"MY SECOND CUSTOM TEXT"
            ]
      ]
$form->populate($data)

表单未填充。

我读过Zend_form不适用于具有相同名称的字段,但在我的情况下,我使用的是数组表示法。我需要使用相同的名称,因为我使用的是数据库中列的名称,所以在我的数据库中,我有两个表"a"answers"b",它们的列名为"field"。

有解决方案吗?

您尝试过使用子窗体吗?我有1.11,所以我不知道,但我成功地实现了你想要的这个代码

/**
 * Form class that should be in application/forms/Foo.php
 */
class Application_Form_Foo extends Zend_Form
{
    public function init()
    {
        $subFormA = new Zend_Form_SubForm();
        $subFormA->addElement($subFormA->createElement('text', 'field', array
        (
            'label' => 'Name (*)',
            'belongsTo' => 'a',
        )));
        $subFormB = new Zend_Form_SubForm();
        $subFormB->addElement($subFormB->createElement('text', 'field', array
        (
            'label' => 'Name (*)',
            'belongsTo' => 'b',
        )));
        $this->addSubForm($subFormA, 'a');
        $this->addSubForm($subFormB, 'b');

        $this->addElement($this->createElement('submit', 'send'));
    }
}

和控制器

/**
 * The controller that both process the request and display the form.
 */
class FooController extends Zend_Controller_Action
{
    public function indexAction()
    {
        // Get the form.
        $foo = new Application_Form_Foo();
        // Poppulate the form from the request.
        if ($foo->isValid($this->getRequest()->getParams()))
        {
            $foo->populate($foo->getValues());
        }
        // Set the form to the view.
        $this->view->form = $foo;
    }
}