Search code examples
phpzend-frameworkmultidimensional-arrayzend-formsubforms

Add multiple subforms of the same type


I'm working with forms and sub forms lately.

I've created the following:

$form = new Application_Form_Cv();
$experience = new Zend_Form_SubForm();
$form->addSubForm($experience, 'experience');

and I do have in my array an element 'experience' thanks to

$form->addSubForm($experience, 'experience');.

When I try the following:

$experience->addSubForm(new Application_Form_Experience(), '0');
$experience->addSubForm(new Application_Form_Experience(), '1');

The object overwrites itself and I get only one 'experience' element and 0 and 1 are not present.

array (
  'controller' => 'cv',
  'action' => 'index',
  'module' => 'default',
  'CvName' => 'Cv Ingenieur informatique',
  'LanguageCode' => 'fr',
  'UserID' => '2',
  'experience' => 
  array (
    'CompanyName' => 'Mondial Assistance Ltd',
    'From' => '2002',
    'Until' => '2009',
    'Current' => '1',
  ),
  'submit' => 'Save CV',
)  

Only Zend_Form_Subforms creates new keys in an array?


Solution

    1. Your Subforms have to extend Zend_Form_SubForm or mimic it's behaviour (set isArray and remove "form"-decorator)
    2. You can't add the idenentical object twice so you have to clone it

    The following snipped should work as expected

    $form = new Application_Form_Cv();
    $experience = new Zend_Form_SubForm();
    $form->addSubForm($experience, 'experience');
    
    $exForm = new Application_Form_Experience();
    $exForm->setIsArray(true);
    $exForm->removeDecorator('form');
    
    $experience->addSubForm($exForm, '0');
    $experience->addSubForm(clone $exForm, '1');
    $experience->addSubForm(clone $exForm, '2');