Reputation: 335
I have two dropdown in a form for selecting department and designation.
$model = new Application_Model_DbTable_Department();
$departments = $model->fetchAll();
$department = $this->createElement('select','department');
$department->setLabel('Department');
$department->setAttrib('class', 'department');
foreach($departments as $d)
$department->addMultiOption($d->id, $d->depname);
$model = new Application_Model_DbTable_Designation();
$designations = $model->fetchAll('depid=1');
$designation = $this->createElement('select','designation');
$designation->setLabel('Designation');
$designation->setAttrib('class', 'designation');
$designation->setRegisterInArrayValidator(false);
foreach($designations as $ds)
$designation->addMultiOption($ds->id, $ds->designation);
I have jquery function to for designation lookup when onchange of department. My problem is when submitting the form if the form has validation error , I need to display the selected designation.
Upvotes: 3
Views: 513
Reputation: 1700
In cases like this, It is best to do the form population after the form has been instantiated. Reason: it is next to impossible to get the values of the form elements on initialization because they do not exist yet (That is, in the init()
method of the Zend_Form
). You could do this:
$form = new Your_Zend_Form();
$designation = $form->getElement('designation');
$departmentId = null;
$request = $this->getRequest();
if($request->isPost()){
$departmentId = $request->getPost('department');
}
$desigantionOptions = $this->_getDesignationOptions($departmentId);
$designation->addMultiOptions($desigantionOptions);
This would be in your controller action or something... But in essence, your designation options would take values from the current department if available from the post or else it would fall to the default selection. The method signature of $this->_getDesignationOptions($departmentId)
will be as follows:
protected function _getDesignationOptions($departmentId = null);
And this would return an array of value/option pair.
Upvotes: 1