Reputation: 14532
I'm using nested Zend\Form\Fieldset
s and Zend\Form\Collection
s, that provide an extremely comfortable way to map complex object structures to the form, in order to get a complete object (ready to be saved) from the form input.
The element I want to add now to my form should represent a list of possible protocols. In the database it's a simple table with columns id
and name
and the objects' structure can be described like Endpoint has Protocol[]
. I defined a MultiCheckbox
(s. below), but I have no idea, how to bind this element to a Protocol
prototype. For a Fieldset
it works via Fieldset\setObject(...)
.
How to get the form processing mechanism of Zend\Form
creating objects from checkboxes?
Code so far:
EndpointFieldset.php
// namespace ...;
// use ....;
class EndpointFieldset extends Fieldset
{
// ...
public function init()
{
parent::init();
$this->add(
[
'type' => 'multi_checkbox',
'name' => 'protocols',
'options' => [
'label' => _('protocols'),
'label_attributes' => [
'class' => 'col-md-1 protocol-field'
],
'value_options' => $this->getValueOptions(),
'selected' => static::PROTOCOLS_DUMMY_VALUE
]
]
);
}
// ...
protected function getValueOptions()
{
$valueOptions = [];
foreach (Protocol::PROTOCOLS as $key => $value) {
$valueOptions[] = [
'value' => $key,
'label' => $value
];
}
return $valueOptions;
}
}
myform.phml
use Zend\Form\View\Helper\FormMultiCheckbox;
echo $this->formMultiCheckbox($myFieldset->get('protocols'), FormMultiCheckbox::LABEL_PREPEND);
UPDATE
I found a workaround for the saving of a new entry: I simply complete the object provided by the form manually and make Protocol
objects from the MultiCheckBox
values. But when I pass complete object to the update form (in order to edit an existing entry), I get a notice and the checkboxes don't get built:
Notice: Object of class My\DataObject\Protocol could not be converted to int in /var/www/path/to/project/vendor/zendframework/zend-form/src/View/Helper/FormMultiCheckbox.php on line 202
My interpretation of this is, that the MultiCheckBox
expects an array with values as primitive types (e.g. int
). Instead it gets an array with Protocol
objects and tries to use its values for in_array(...)
-- and that cannot work.
Upvotes: 3
Views: 318