Zend form multiselect repopulate after validation error
I have a Zend form multiselect element which I am creating like this
$this->addElement('multiselect','somedates',array(
'filters'=>array('StringTrim'),
'required'=>true,
'label'=>'Dates',
'style' => 'width:14em',
'size'=>'4',
'RegisterInArrayValidator' => false, //otherwise it gives an error
));
then I add some multi options into the multi-select dynamically through JavaScript into the multi-select (basically a YUI calendar where a user clicks on a date and that gets into multi-select as an option)
Everything works fine if I give all the required values to the form an开发者_StackOverflowd it passes the isValid test however, if there is an error, every other element gets repopulated with whatever was submitted but multi-select looses all it's options and has to be re-populated by the user itself. Multi-select appears to be going fine as this is what i get if I var dump $this->getRequest()->getQuery();
this is what I get ["somedates"]=> array(2) { [0]=> string(10) "2010-09-09" [1]=> string(10) "2010-09-10" }
I am just wondering if anybody else had the same experience and know what is going wrong over here or if the Zend Framework is capabale of repopulating the multi-selects.
The problem is that ZF expects the user to select one of the options that you populated the ZF MultiSelect
with. When you add an option using Javascript, ZF does not know that this is now a valid option so the validation will fail. To get around this you need remove the InArray
validator
$this->getElement("somedates")->removeDecorator("InArray");
As for populating the array again, you need to save these somewhere once the user adds them, so if the form fails ZF can add them back in again. You could append these to a hidden
field, when the form is submitted check this hidden field for values and add these dates back into the MultiSelect
input.
Make sure you validate the input from the hidden field, do not assume that is does contain a correct date.
You know the form gets populated when you call the
$form->isValid($this->getRequest()->getPost()/getQuery
But your multi-select won´t get populated unless you do the following:
$form->getElement('somedates')
->addMultiOptions($datesToGetItRepopulated);
I believe you have no problem with the form sending the options (the added ones too) of the multiselect in the Post parameters, right?
In order for the addMultiOptions() to work, have in mind that your array should have the following format:
$datesToGetItRepopulated = array(
array('key'=>heresGoesWhatYouwantAsTheValueForYourOption,
'value'=>hereGoesWhatYouWantAsTextForYourOption),
array('key'=>balbla, 'value'=>blabla)
....
);
As you can see, before calling the addMultiOptions(...) method, you are going to have to, from the server, manipulate the information you've received for the 'somedates' so it stands to this kind of array. That way the Zend_Form_Element_MultiSelect will know how to populate it with options.
精彩评论