My Zend\Form
includes a Zend\Form\Element\Select
with the attribute 'multiple' => 'multiple'
and a NotEmpty
validator with a custom isEmpty
error message.
With the multiple attribute set, when I submit the form without selecting any options, I get the default "Value is required..." error message rather than my own.
When I remove the multiple
attribute, I get the desired behavior, i.e., my custom error message.
So, what I am doing wrong?
Here is the quick-and-dirty test, with everything stuffed into my controller action for the sake of demonstration:
public function testAction() {
$form = new \Zend\Form\Form;
$factory = new \Zend\InputFilter\Factory;
$form->add(
[
'name' => 'select',
'type' => 'Zend\Form\Element\Select',
'attributes' => [
'multiple' => 'multiple',
],
'options' =>[
'value_options' => ['' => '', 1 => "one", 2 => "two", 3 => "three"],
]
]
);
$filter = $factory->createInputFilter([
'select' => [
'name' => 'select',
'required' => true,
'filters' => [
['name' => 'StringTrim',],
],
'validators' => [[
'name' => 'NotEmpty',
'options' => ['messages' => ['isEmpty'=> 'all Dharmas are forms of Emptiness']],
]],
]
]);
$form->setInputFilter($filter);
$form->add(['name'=> 'submit','type'=> 'submit', 'attributes'=> ['value'=> 'submit']]);
$form->setAttribute('action','/my-project/index/test')
$view = new ViewModel();
$view->setTemplate('my-project/index/test')
->setVariables(['form' => $form]);
if ($this->getRequest()->isPost()) {
$data = $this->params()->fromPost();
$form->setData($data);
print_r($data); // just making sure, for sanity's sake
if ($form->isValid()) {
echo "valid!";
} else {
echo "validation failed.";
}
}
return $view;
}
Just for the record, here is the view, although I know (from dumping the error messages) that the issue is not here:
<?php
$form = $this->form;
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formCollection($form);
echo $this->form()->closeTag();
Thanks!