0
votes

I have a problem with form element select in ZF2. I create query doctrine 2 and have good results objects list.

$langs = $this->getEntityManager()->getRepository('Application\Entity\Langs')->findAll();

And create simple form:

class Coupon extends Form
{
    protected $objectManager;

    public function __construct($name = null)
    {        
        parent::__construct('coupon');

        $this->setAttribute('method', 'post');

        $this
             ->setAttribute('method', 'post')
             ->setHydrator(new ClassMethodsHydrator(false))
         ;

    $this->add(array(
            'name' => 'id',
            'attributes' => array(
                'type'  => 'hidden',
            ),
        ));
     }

   $this->add(array(
         'type' => 'Zend\Form\Element\Select',
         'name' => 'language',
         'attributes' => array(
             'class' => 'form-control',
         ),
         'options' => array(
                 'label' => 'default.form.message',
                 'empty_option'    => '--- choose formElementName ---',
                 'value_options' => array(
                         '0' => 'French',
                         '1' => 'English',
                         '2' => 'Japanese',
                         '3' => 'Chinese',
                 ),
         )
    ));

}

How can convert result ($langs) to array for value_options - zend element select? What should I use for this?

1
Since you're using Doctrine, you may want to check out ObjectSelect-Form-ElementSam
THX, it was good trail :)sebob

1 Answers

0
votes

I resolve it.

I create

public function getFormElementConfig()
    {

        return array(
            'invokables' => array(
                'Coupon' => 'Application\Form\Langs',
            ),
            'initializers' => array(
                'ObjectManagerInitializer' => function ($element, $formElements) {
                    if ($element instanceof ObjectManagerAwareInterface) {

                        $services      = $formElements->getServiceLocator();
                        $entityManager = $services->get('Doctrine\ORM\EntityManager');
                        $element->setObjectManager($entityManager);
                    }
                },
            ),
        );

and add init in form:

public function init()
    {
        parent::init();

        $this->add(
            array(
                'type' => 'DoctrineModule\Form\Element\ObjectSelect',
                'name' => 'messages',
                'options' => array(
                    'object_manager' => $this->getObjectManager(),
                    'target_class'   => 'Application\Entity\Langs',
                    'property'       => 'title',
                ),
            )
        );
    }

It works :) Thx Sam.