Zend Framework: isValid() clears values from disabled form fields!
When you submit a form, disabled form fields are not submitted in the request.
So if your form has a disabled form field, it makes working with Zend_Form::isValid()
a little frustrating.
$form->populate($originalData);
$form->my_text_field->disabled = 'disabled';
if (!$form->isValid($_POST)) {
//form is not valid
//since my_text_field is disabled, it doesn't get submitted in the request
//isValid() will clear the disabled field value, so now we have to re-populate the field
$form->my_t开发者_StackOverflow社区ext_field->value($originalData['my_text_field']);
$this->view->form = $form;
return;
}
// if the form is valid, and we call $form->getValues() to save the data, our disabled field value has been cleared!
Without having to re-populate the form, and create duplicate lines of code, what is the best way to approach this problem?
Are you setting the element to disabled so that the user can't edit it's contents but only to see it? If so, just set the element's readonly attribute to true, I think it'll work that way.
I use a custom class inherited from Zend_Form. Class adds some features and solves this problem by replacing the method isValid as follows:
class Murdej_Form extends Zend_Form {
function isValid($data) {
$_data = $this->getValues();
$valid = parent::isValid($data);
$this->populate($_data);
return $valid;
};
};
instead of using isValid()
we can use isValidPartial()
. Unlike isValid()
, however, if a particular key is not present, it will not run validations for that particular element. So, isValidPartial()
will not validate for disabled fields.
Reference: ZF Documentation
精彩评论