views:

117

answers:

2

I'm trying to create 1 base form in Zend which is a part of many other forms. Eg: the following 3 elements could be a sub form or a mini form that is a part of a larger form : -Name -Age -Address

I just want to re-use the same form in different places - at times adding elements like 'shipping address' etc I'm getting stuck at the data submission point - when i use multiple forms, i cannot have multiple submit buttons - just one. So obviously all the data is not getting captured - just the data of the form which does contain the sub-form.

Any thoughts here? I have used Zend_Form in the past - but never like this.

+1  A: 

You should build up a single Zend_Form object. If you wan to append your Name, Age, and Address to a form and have them look normal, do this:

$display_form = new DisplayForm();
$naa_form = new NameAgeAddressForm();
$display_form->addElements( $naa_form->getElements() );

If you'd like them to look like a sub-form (i.e. kinda grouped together in a sub unit), do this:

$display_form = new DisplayForm();
$display_form->addSubForm( new NameAgeAddressForm() );
Derek Illchuk
A: 

Set up your reusable Name/Age/Address form like so (most likely in the init() method of an extension, so you wouldn't see most of this code in your action.)

$littleForm = new Zend_Form();
$littleForm->addElement(new Zend_Form_Element_Text('name'));
$littleForm->addElement(new Zend_Form_Element_Text('age'));
$littleForm->addElement(new Zend_Form_Element_Text('address'));
$littleForm->addElement(new Zend_Form_Element_Submit('submit'));

Since you don't need any other decorators for the NAA form, you set FormElements as the only decorator and remove the submit button from the NAA form

$littleForm->setDecorators(array('FormElements'));
$littleForm->removeElement('submit');

Set up your display/main form like so, and set the order of the NAA form when you add it as a subForm so it displays above the elements of the main form.

$bigForm = new Zend_Form();
$bigForm->addElement(new Zend_Form_Element_Text('shippingAddress'));
$bigForm->addElement(new Zend_Form_Element_Submit('submit'));
$bigForm->addSubForm($littleForm, 'littleForm', 1);

$this->view->form = $bigForm;

Display the form in the view script

echo $this->form;

That's how you do it using decorators. Personally, I cheat and display my forms through a partial script and only use the decorators to render the input elements. Probably you'd want labels and things too...

Robin Canaday
Thank you very very much - this worked!
anu iyer