Zend_Form array notation and empty elements names
Asked Answered
W

2

5

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?

Widera answered 28/10, 2009 at 17:13 Comment(1)
I want the same! Please let me know if you solve it.Scroop
S
7

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

Seem answered 16/5, 2011 at 18:34 Comment(0)
D
0

class MyFooForm extends Zend_Form { public function init() { $fullNameOpts = array( 'required'=>false, 'label'=>'fullName', 'isArray'=>true, 'validators' => array( array('stringLength', false, array(1, 250) ) ) ); $this->addElement('text' ,'fullName',$fullNameOpts); // rest of the elements , forms and stuff goes here } }

And that does creates

<dd id="fullName-element"><input type="text" class="inputAccesible" value="" id="fullName"name="fullName[]"></dd>

It's on Element.php , in Form , line 512 "isArray" check. I'm using a regular zend_form, crossValidation with custom validators and i'm pushing subforms to replicate the main form, 'cause the user can add multiple times the same form. Additionally , I'm too lazy to research custom decorators, i have created one, but it kills subForms and array notation, so i just stick with the regular ones, and that solves it.

I'm at Zf 1.10.

Deason answered 22/6, 2010 at 1:34 Comment(2)
But generally, when we make use of empty array notation, we have many fields with the same name. If you try to create a new element with the same name expecting a new field fullName[] this does not workScroop
Post some code and I'll give you a hand :). I made a lib to deal with this, and my next goal is particularly that. You have one form, and you want to replicate only 1 element of the form.Mysterious

© 2022 - 2024 — McMap. All rights reserved.