views:

307

answers:

1

Hello, I have form, where some fields are looks like rows, so I can add/delete them using JS. For example:

Field with ID=1 (existing row)

<input id="id[1]" type="text" name="id[1]" value="1" />
<input id="name[1]" type="text" name="name[1]" value="100" />

Field with ID=2 (existing row)

<input id="name[2]" type="text" name="name[2]" value="200" />
<input id="name[2]" type="text" name="name[2]" value="200" />

new row created by default (to allow add one more row to existing rows)

<input id="id[n0]" type="text" name="id[n0]" value="" />
<input id="name[n0]" type="text" name="name[n0]" value="" />

new row created by JS

<input id="id[n1]" type="text" name="id[n1]" value="" />
<input id="name[n1]" type="text" name="name[n1]" value="" />

So than we will proceed form, we will know what rows to update and what to add (if index starts with "n" - new, if index is number - existent element).

I tried subforms... but do I have to create subform for each field? If I use following code:

$subForm = new Zend_Form_SubForm();
$subForm->addElement('Text', 'n0');
$this->addSubForm($subForm, 'pid');       
$subForm = new Zend_Form_SubForm();
$subForm->addElement('Text', 'n0');
$this->addSubForm($subForm, 'name');

What is the best way for this?

1) Use subforms?

2) Extend Zend/Form/Decorator/ViewHelper.php to use names like name[nX]?

3) Other solutions?

Thanks.

+1  A: 

The alternative is to create a single sub form with all the fields in place and then add an array of these sub forms to your main form. This is the code I use for that:

        foreach ($value as $id => $row) {

                $subForm = clone $origSubForm;

                $name = 'multi[' . $id . ']';
                $subForm->setElementsBelongTo($name);
                $subForm->setName($name);
                $subForm->populate($row);

                $subForms[$id] = $subForm;
        }

Put these forms in an array element (in this example named multi). Instead of arrays containing the individual $id[] values you get one array containing [0 => ['id' => .., ], 'n0' => ['id' => ...]]

Matijs
Thanks. it's what I need.