I have a zend form submitted by ajax:
$.ajax({
data:{'async':$('#form').serializeArray()},
type:"POST",
async: true,
success: function(data) {
$("#container").html(data);
},
failure: function(data) {
alert('error');
}
});
In order to validate the form, I have to pass the data to the Zend function setData()
:
$form->setData($request->getPost('async'));
if (! $form->isValid()) { /*do stuff*/}
The only problem is that - when the form contains fieldsets - the setData expected array should be:
array{
filedset1=aray{
el_1.1=>'value',
el_1.2=>'value',
[...]
},
filedset2=aray{
el_2.1=>'value',
el_2.2=>'value',
[...]
},
[...]
};
...while the array given by jquery is (that's correct, that's how zend assigns names to the fieldsets children):
array{
filedset1[el_1.1]=>'value',
filedset1[el_1.2]=>'value',
[...]
filedset2[el_2.1]=>'value',
filedset2[el_2.2]=>'value',
[...]
};
I managed to convert the array format this way:
$form->setData($this->parseSerializedArray($request->getPost('async')));
if (! $form->isValid()) { /*do stuff*/}
[...]
public function parseSerializedArray($array)
{
$result=array();
foreach($array as $item){
if (preg_match("/^\w+\[\w+\]$/",$item['name'])){
$str=explode("[",$item['name']);
$key=$str[0];
$val=rtrim($str[1],']');
if (!array_key_exists($key,$result)){$result[$key]=array();}
$result[$key][$val]=$item['value'];
}
//if the element doesn't belong to any fielset...
else{$result[$item['name']]=$item['value'];}
}
return $result;
}
Do you know a simplier/better way to do that?
To answer to my own question:
the actual problem is the jquery function
serializeArray()
which seems to be unable to correctly interpretate the names with square bracklets.A simpler solution could be:
Jquery: replace
serializeArray()
withserialize()
:Php: parse the string with the built-in funcion
parse_str