I am building a form using Zend_Form ... i need to add some fields to the form dynamically (jquery/ajax) ... i created a subform for each set of fields that need to be created at runtime ...
to get my elements in an array with correct names like subform1[index][element]
, i added 2 more subform :
subform1 : a wrapper rendered as a field set
subform2 : a container that plays the index
part of the names
elements subform : this is main subform that holds the elements
the subform2 and elements part gets repeated for each set of new elements ...
now everything works fine when form is created and rendered in the view , i get the correct names (subform1[index][element]
) ...
but when i use ajax to generate new elements i don't know how to render the form and get the subform2 part with correct names ...
this is the function that creates the subforms :
private function makeSubForm($id, $legend)
{
$wrapper = new Zend_Form_SubForm();
$wrapper->setOptions(array('legend' => $legend, 'class' => 'ui-corner-all multi_value'))
->setIsArray(true);
$array = $this->_getArray($id);
//-------------------------LOOP--------------------------
$form_name = "Application_Form_Employ_$id";
// var_dump($array);
foreach ($array as $key => $value) {
$form = new $form_name();
$container = new Zend_Form_SubForm();
$container->setOptions(array('class' => 'subform'))
->setIsArray(true)
->addSubForm($form, 'xxxxx');
$wrapper->addSubForm($container, $key);
}
Zend_Registry::get('session')->{$id} = $array;
//----------------------------------------------------------
$this->addSubForm($wrapper, $id);
}
and this is my action method :
public function newElementAction()
{
$this->_disableView();
$id = $this->getRequest()->getParam('id');
$form = new Application_Form_Employment();
$params = array();
$keys = Zend_Registry::get('session')->{$id};
$lastKey = end(array_keys($keys));
$keys[++$lastKey] = array();
$params[$id] = $keys;
// var_dump($params);
$form->create($params);
// $form->render();
$this->_response->appendBody($form->getSubForm($id)->getSubForm($lastKey));
}
with this code i get subform2[element]
as my names ...
but if i uncomment $form->render();
i get subform1[subform2][subform1][subform2][element]
so how can i get the second subform's HTML with correct names ?
well i found a hack to get what i want but i am looking for a better way ...
public function newElementAction()
{
$this->_disableView();
$id = $this->getRequest()->getParam('id');
$form = new Application_Form_Employment();
$params = array();
$keys = Zend_Registry::get('session')->{$id};
$lastKey = end(array_keys($keys));
$keys = array(++$lastKey => array());
$params[$id] = $keys;
$form->create($params, $id);
$this->_response->appendBody($form->{$id});
}
i created only the last child and outputed the parent and in the client side removed the parents markup before inserting into page ...
there has to be a solid way to just render the subform with its parents indexes intact !!??