ZF2-476: Fatal error: Uncaught exception 'Zend\Form\Exception\InvalidArgumentException' with message 'Zend\Form\View\Helper\FormCheckbox::render requires that the element is of type Zend\Form\Element\Checkbox'
Description
This is related to issue #ZF2-457. Tested against zendframework-zf2-release-2.0.0rc4-2-g5dd58b8.
ZF2-457 was resolved by requiring the element to be of type Zend\Form\Element\Checkbox,
but Zend\Form\Form will return a Zend\Form\Element with get() if the element was added using add(array(...)).
However, if the element is first created and added using add($element), get() will return the correct type. Note that this applies to all other elements as well, eg. radio, text, etc. It seems safer to create the element and add it to the form rather than passing in an array of options.
// sample form which has 2 checkbox elements added in different ways
namespace Web\Form;
use Zend\Form\Form;
class Test extends Form
{
public function __construct($name = null)
{
parent::__construct($name);
$this->setAttribute('method', 'post');
// adds element of type Zend\Form\Element
$this->add(array(
'name' => 'problemCheckbox',
'attributes' => array(
'type' => 'checkbox',
'checked' => false,
),
'options' => array(
'label' => 'Problem option',
),
));
// adds element of type Zend\Form\Element\Checkbox
$element = new \Zend\Form\Element\Checkbox('goodCheckbox');
$this->add($element);
}
}
// sample controller action
public testAction()
{
$form = new \Web\Form\Test();
// returns object of Zend\Form\Element
var_dump($form->get('problemCheckbox'));
// returns object of type Zend\Form\Element\Checkbox
var_dump($form->get('goodCheckbox'));
return array('form' => $form);
}
// sample view script
<?php
// causes fatal error as shown in Summary as get() returns Zend\Form\Element
echo $this->formCheckbox($form->get('problemCheckbox'));
// no problems as get() returns Zend\Form\Element\Checkbox
echo $this->formCheckbox($form->get('goodCheckbox'));
?>
Comments
Posted by Chris Martin (cgmartin) on 2012-08-19T20:03:26.000+0000
You can get around this by adding a 'type' to the element factory array:
Posted by Zion Ng (kitthrng) on 2012-08-20T00:21:51.000+0000
Thanks, it works! It would be useful to point this out in the API or tutorial. Currently there seems no documentation stating the keys that can be used when passing in an array to add().
Posted by Chris Martin (cgmartin) on 2012-08-20T00:39:04.000+0000
Changing issue type to Docs: Improvement.
Posted by Ralph Schindler (ralph) on 2012-10-08T20:14:57.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/2530