Search code examples
zend-formzend-form-sub-form

Zend_Form array notation and empty elements names


I'want to render:

<input type="text" value="" name="foo[]" />
<input type="text" value="" name="bar[]" />

but Zend_Form_Element require a (string) name, so I need to do:

$this->addElement('text', '1', array(
    'belongsTo' => 'foo'
));

$this->addElement('text', '2', array(
    'belongsTo' => 'bar'
));

but the output is:

<input id="foo-1" type="text" value="" name="foo[1]" />
<input id="bar-2"  type="text" value="" name="bar[2]" />

I can also accept an output like:

<input id="foo-1" type="text" value="" name="foo[1]" />
<input id="bar-1"  type="text" value="" name="bar[1]" />

but Zend_Form_Element rewrite elements with the same name

is there a way to do what I need?


Solution

  • For multiple values:

    $foo = new Zend_Form_Element_Text('foo');
    // Other parameters
    $foo->setIsArray(TRUE);
    $this->addElement($foo);
    

    Generates: name="foo[]"

    --

    If you're looking for given keys such as name="foo[bar]", use:

    $bar= new Zend_Form_Element_Text('bar');
    // Other parameters
    $bar->setBelongsTo('foo');
    $this->addElement($bar);
    

    --

    Tested on ZF 1.11.5