views:

127

answers:

2

I have a Zend_Form that has 4 or more subforms.

/** Code Snippet **/ $bigForm = new Zend_Form();

    $littleForm1 = new Form_LittleForm1();
    $littleForm1->setMethod('post');

    $littleForm2 = new Form_LittleForm2();
    $littleForm2->setMethod('post');

    $bigForm->addSubForm($littleForm1,'littleForm1',0);
    $bigForm->addSubForm($littleForm2,'littleForm2',0);

On clicking the 'submit' button, I'm trying to print out the values entered into the forms, like so:

/** Code snippet, currently not validating, just printing **/

if($this->_request->getPost()){ $formData = array();

  foreach($bigForm->getSubForms() as $subForm){
        $formData = array_merge($formData, $subForm->getValues());      
  }
  /* Testing */
  echo "<pre>";
  print_r($formData);
  echo "</pre>";

}

The end result is that - all the elements in the form do get printed, but the values entered before posting the form don't get printed.

Any thoughts are appreciated...I have run around circles working on this!

Thanks in advance!

A: 

A Zend_Form does not automatically retrieve values from the $_POST variable. Use:

$bigform->populate($_POST)

Or alternatively:

$bigform->populate($this->_request->getPost())

Another thing to keep in mind is that if the sub forms contain elements with the same name they will clash. To check this use the option View => Page Source in your browser and look at the HTML that is generated. When you see two <input> elements with the same name attribute, then this is the problem.

The Zend solution for this is to give the sub form elements different names using setElementsBelongTo:

$littleForm1->setElementsBelongTo('littleForm1');
$littleForm2->setElementsBelongTo('littleForm2');

Furthermore you should leave out these calls as they serve no purpose (but you should set them for the $bigForm):

$littleForm->setMethod('post');
Matijs
I tried this, and hit a new problem - the above is not working as the $_POST seems on only have the last subform's values - i.e. it has $littleForm2, but not $littleForm1's values.I'm not sure why that is, if you have any thoughts on that, I'd appreciate it.
anu iyer
I adapted the solution to what is probably your problem. Good luck.
Matijs
+1  A: 

This is what I did -

$bigForm->addElements($littleForm1->getElements());

Then, iterated over the form elements like so:

    $displayGroup1 = array();

    foreach($bigForm->getElements() as $name=>$value){

        array_push($displayGroup1, $name);
    }

Then, add a displayGroup to $bigForm:

   $bigForm->addDisplayGroup($displayGroup1, 'test',array('legend'=>'Test'));

And repeat for multiple display groups.

I'm sure there is a better way to do it, but I'm currently unable to find one out. This is currently one way I can think of to retrieve all the form values via $_POST, if a form is made up of one or more subforms. If any one knows of a better solution, please post it!

anu iyer