ZF2-571: Validation fails on multi_checkbox form type when nothing is checked.
Description
If I create a form element of type MultiCheckbox, form submission will fail with a validation error when none of the checkboxes are selected, with a "Value is required and can't be empty" message.
Example:
// Build a name element.
$name = new Element('name');
$name->setLabel('Your name');
$name->setAttributes(array(
'type' => 'text'
));
// Build a submit button element.
$send = new Element('send');
$send->setLabel('Send');
$send->setAttributes(array(
'type' => 'submit',
'value' => 'Send'
));
// Build a checkbox element.
$check = new Checkbox('check');
$check->setLabel('Checkbox example');
// Build a multi-checkbox element.
$multicheck = new MultiCheckbox('multicheck');
$multicheck->setLabel('Multi checkbox example');
$multicheck->setOptions(array(
'value_options' => array(
'One' => 'one',
'Two' => 'two',
),
));
// Assemble the form.
$form = new Form('contact');
$form->add($name);
$form->add($check);
$form->add($multicheck);
$form->add($send);
// Get the request if any.
$request = $this->getRequest();
$data = $request->getPost();
$form->setData($data);
// Validate the form
if ($form->isValid()) {
$validatedData = $form->getData();
$success = 'Form submit was successful';
} else {
$success = 'Form submit failed';
$messages = $form->getMessages();
}
Validation will always fail in this case on the multicheck element.
--
The function {{getInputSpecification}} in Zend/Form/Element/Checkbox.php is the culprit as it sets "required" to true. Although "required" is not problematic for Checkbox elements it is a problem for multicheck elements because of the way the input data is returned to the form.
I suggest either:
- Change {{getInputSpecification}} in Checkbox.php to set 'required' to be false, because checkboxes will have a checkedvalue and an uncheckedvalue and so this test is never hit for checkboxes.
- Override {{getInputSpecification}} in MultiCheckbox.php to set 'required' to be false.
Comments
Posted by Del Elson (delatbabel) on 2012-09-19T04:21:52.000+0000
The attached files add to / replace those in the Zend Framework Skeleton Application to illustrate the issue.
module/Application/src/Application/Controller/IndexController.php
module/Application/view/application/index/form.phtml
module/Application/config/module.config.php
Posted by Frank Brückner (frosch) on 2012-09-19T06:14:02.000+0000
Code tags added.
Posted by Del Elson (delatbabel) on 2012-09-21T01:31:39.000+0000
Added the simplest fix for this at https://github.com/zendframework/zf2/pull/2395
Posted by Ralph Schindler (ralph) on 2012-10-08T20:12:21.000+0000
This issue has been closed on Jira and moved to GitHub for issue tracking. To continue following the resolution of this issues, please visit: https://github.com/zendframework/zf2/issues/2596