ram
ram

Reputation: 15

inject entitymanager in form type using service

I use symfony2.7 and I have a problem when I want to inject the entitymanager into the formtype but I don't see that __construct() is called on my service, and injection doesn't work. I use a service to inject the entitymanager into my formtype like this.

public function createValeurChampNomenclatureAction(Request $request) {
        $em = $this->getDoctrine()->getManager();        
        $cgaValeurChampNomenclature = new CGAValeurchampnomenclature();
        $form = $this->createForm('espritApp_nomenclaturebundle_cgavaleurchampnomenclature', $CGAValeurChampNomenclature);
....

and in my formtype I have create my construct

     class CGAValeurChampNomenclatureType extends AbstractType
{

  /**
 * @var EntityManager $entityManager Entity manager
 */
    private $em;

    /**
 * Constructor
 *
 * @param EntityManager $entityManager Entity manager
 */
    public function _construct(EntityManager $entityManager)
    {
        $this->em=$entityManager;


    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add('cgatypenome','entity', array(
                    'class' => 'EspritAppNomenclatureBundle:CGATypenomenclature',
                    'property' => 'codeStr',
                    'multiple'  => false,
                    'required'    => true,
                    'attr'=> array('class'=>'form-control select2 codeStr'))
                    )
            ->add('cgacodenomenclature','choice', array('required' => TRUE,
             'attr' => array('placeholder' => 'Code nomenclature','class'=>'form-control select2 codeNomenclature')
                ))
          ->add('cgachamptypenome','choice', array('required' => TRUE,
             'attr' => array('placeholder' => 'Code Champ','class'=>'form-control select2 codeChampNomenclature')
                ))
         ->add('chaCodeStr','text', array('required' => TRUE,
             'attr' => array('placeholder' => 'Champ code Str','class'=>'form-control')
                ))
                ->add('valeur','text', array('required' => TRUE,
             'attr' => array('placeholder' => 'valeur','class'=>'form-control')
                ));


        $formModif = function (FormInterface $form, $codeStr) 
        {             
            $listChampTypeNome = $this->em->getRepository('EspritAppNomenclatureBundle:CGAChamptypenomenclature')->getListChampTypeNomenclatureByCodeStr($codeStr);                       
            $listCodeNome = $this->em->getRepository('EspritAppNomenclatureBundle:CGACodenomenclature')->getListCodeNomenclatureByCodeStr($codeStr);

             if ($listChampTypeNome) {
                $ChampsTypeNome = array();
                foreach($listChampTypeNome as $ChampTypeNome) {
                    $ChampsTypeNome[] = $ChampTypeNome->getCodeChamp();                   
                }
            } else {
                $ChampsTypeNome = null;
            }


             if ($listCodeNome) {
                $CodesNome = array();
                foreach($listCodeNome as $CodeNome) {
                    $CodesNome[] = $CodeNome->getCodeNome();                   
                }
            } else {
                $CodesNome = null;
            }


            $form->add('cgacodenomenclature','choice', array('required' => TRUE,
             'attr' => array('placeholder' => 'Code nomenclature','class'=>'form-control select2 codeNomenclature'),'choices' =>$ChampsTypeNome)
                )
                ->add('cgachamptypenome','choice', array('required' => TRUE,
             'attr' => array('placeholder' => 'Code Champ','class'=>'form-control select2 codeChampNomenclature'),'choices'=>$CodesNome)
                );
        };

        $builder->get('cgacodenomenclature')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($formModif){
            $formModif($event->getForm()->getParent(),$event->getForm()->getData());
        });




    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'EspritApp\NomenclatureBundle\Entity\CGAValeurchampnomenclature'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'espritApp_nomenclaturebundle_cgavaleurchampnomenclature';
    }
}

and this my service in services.yml

 app.form.type.cgavaleurchampnome:
        class:  EspritApp\NomenclatureBundle\Form\CGAValeurChampNomenclatureType
        tags:
            - { name: form.type, alias: espritApp_nomenclaturebundle_cgavaleurchampnomenclature }
        arguments: [@doctrine.orm.entity_manager]

the problem that I got this Error:

Call to a member function getRepository() on a non-object

Upvotes: 0

Views: 1293

Answers (2)

Logans
Logans

Reputation: 119

You can easily define form as service and pass there EntityManager. For that you should define getName function in form type like that:

/**
 * {@inheritdoc}
 */
public function getName()
{
    return 'my_form';
} 

And define this form type as service:

app.form.task:
    class: AppBundle\Form\Type\MyFormType
    tags:
        - { name: form.type, alias: my_form }
    arguments:
        - "@doctrine.orm.entity_manager"

After that, you can get EntityManager object in constructor and use it in whole form.

/**
 * @var EntityManager $entityManager Entity manager
 */
private $em;

/**
 * Constructor
 *
 * @param EntityManager $entityManager Entity manager
 */
public function __construct(EntityManager $entityManager)
{
    $this->em = $entityManager;
}

Usage example:

/**
 * {@inheritdoc}
 */
public function finishView(FormView $view, FormInterface $form, array $options)
{
    $users = $this->em->getRepository('AppBundle:User')->findAll();

    $view->vars['users'] = $users;
}

Also now you can use form type in controller like this:

$form = $this->createForm('my_form');

Is that what you're looking for?

Upvotes: 0

Cerad
Cerad

Reputation: 48865

I suspect you need a use statement to access $em here:

$em = $this->em;
$formModif = function (FormInterface $form, $codeStr ) use $em
{
  die(get_class($em));

Though it is rather puzzling why you are doing this. http://php.net/manual/en/functions.anonymous.php

Upvotes: 1

Related Questions