user4787666
user4787666

Reputation:

Doctrine 2 customize ObjectMultiCheckbox values

How can I custom values with DoctrineModule\Form\Element\ObjectMultiCheckbox?

I used Zend\Form\Element\MultiCheckbox and I set values like this:

$this->add(array(
    'type' => 'Zend\Form\Element\MultiCheckbox',
    'name' => 'countries',
    'options' => array(
        'label' => 'Select countries',
        'value_options' => array(
            'value' => 1,
            'label' => 'United Kingdom',
            'continent' => 'Europe'
        )
    )
))

But now I need to use Doctrine 2 Multicheckbox and I need to set custom value options. How can i do this?

I have currently only this:

$this->add(array(
    'type' => 'DoctrineModule\Form\Element\ObjectMultiCheckbox',
    'name' => 'countries',
    'options' => array(
        'object_manager' => $this->em,
        'target_class'   => 'Module\Entity\Country'
    )
));

I need this for custom view render. I want to show countries like this:

Europe
- Sweden
- United Kingdom
- and others...

America
- Canada
- United States
- other countries...

Upvotes: 11

Views: 729

Answers (1)

user4787666
user4787666

Reputation:

SOLVED!

I created a new form element:

ObjectMultiCheckbox:

namespace Application\Form\Element;

use Zend\Form\Element\MultiCheckbox;
use Zend\Stdlib\ArrayUtils;

class ObjectMultiCheckbox extends MultiCheckbox
{
    public function setValue($value)
    {
        if ($value instanceof \Traversable)
        {
            $value = ArrayUtils::iteratorToArray($value);

            foreach ($value as $key => $row)
            {
                $values[] = $row->getId();
            }

            return parent::setValue($values);
        }
        elseif ($value == null)
        {
            return parent::setValue(array());
        }
        elseif (!is_array($value))
        {
            return parent::setValue((array)$value);
        }
    }
}

It's not really pretty, but it handle object to the form as DoctrineModule\Form\Element\ObjectMultiCheckbox.

My entity which using this code have always identifier 'id' so I can use static code as like this: $row->getId(); It's ugly, but it works!

Upvotes: 2

Related Questions