3

我有两个用于选择部门和名称的下拉列表。

$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);

我有 jquery 功能,用于在更改部门时进行指定查找。我的问题是提交表单时,如果表单有验证错误,我需要显示选定的名称。

4

1 回答 1

1

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.

于 2012-10-30T11:20:25.533 回答