N
N
NubasLol2018-07-21 15:51:47
symfony
NubasLol, 2018-07-21 15:51:47

Symfony how to properly create a form for M:M?

Field to fill

/**
     * @ORM\ManyToMany(targetEntity="Department", inversedBy="employees")
     */
    private $departments;

I do it like this:
$em = $this->getDoctrine()->getManager();

        $departmentArray = $em->getRepository('AppBundle:Department')->findAll();

        $employee = new Employee();
        $form = $this->createForm(new EmployeeType(), $employee, [
            'departmentArray' => $departmentArray,
        ]);

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $departmentArray  = $options['departmentArray'];

            ->add('departments', ChoiceType::class,
                array(
                    'choices' => $departmentArray,
                    'choices_as_values' => true,
                    'expanded' => true,
                    'multiple' => true,
                    'label' => false,
                    'required' => true,
                    'choice_label' => function($department, $key, $value) {
                        return strtoupper($department->getName());
                    },
                ))

Result:
Expected argument of type "string", "AppBundle\Form\EmployeeType" given
Requires a string, although it actually needs an object. How to fight?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question