0

I'm struggling with symfony forms. I want to build a form for an user. This user as a arraycollection field that gather products (nom, description).

I would like to create a form that create a checkbox for each of the products passed to the form builder. Actually it just created input fields without labels... Here is the code of my UserType class :

public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder->add('nom')->add('prenom')->add('mail')->add('tel1')->add('tel2', TextType::class, array('required' => false))
        ->add('username')->add('password', PasswordType::class)
        ->add('groupe', ChoiceType::class, array(
            'choices' => array('Administrateur' => 'ROLE_SUPER_ADMIN', 'Gérant' => 'ROLE_ADMIN', 'Opérateur' => 'ROLE_USER'),
            'expanded' => true,
        ))
        ->add('produits', CollectionType::class, array(
            'entry_type' => ProduitType::class
        ))
    ;
}

/**
 * {@inheritdoc}
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => User::class
    ));
}

/**
 * {@inheritdoc}
 */
public function getBlockPrefix()
{
    return 'gestcoupons_userbundle_user';
}

Here is my ProduuctType code :

public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder->add('nom')->add('prenom')->add('mail')->add('tel1')->add('tel2', TextType::class, array('required' => false))
        ->add('username')->add('password', PasswordType::class)
        ->add('groupe', ChoiceType::class, array(
            'choices' => array('Administrateur' => 'ROLE_SUPER_ADMIN', 'Gérant' => 'ROLE_ADMIN', 'Opérateur' => 'ROLE_USER'),
            'expanded' => true,
        ))
        ->add('produits', CollectionType::class, array(
            'entry_type' => ProduitType::class
        ))
    ;
}

/**
 * {@inheritdoc}
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => User::class
    ));
}

/**
 * {@inheritdoc}
 */
public function getBlockPrefix()
{
    return 'gestcoupons_userbundle_user';
}

Here is my UserController code :

public function ajouterAction(Request $request){

    $this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');
    $em = $this->getDoctrine()->getManager();
    $produits = $em->getRepository('ProduitBundle:Produit')->findAll();
    $societes = $em->getRepository('SocieteBundle:Societe')->findAll();
    $user = new User();
    foreach ($produits as $produit) {
        $user->getProduits()->add($produit);
    }
    $form = $this->createForm('GestCoupons\UserBundle\Form\UserType', $user);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($user);
        $em->flush($user);

        return $this->redirect('dashboard_admin');
    }

    return $this->render('user/new.html.twig', array(
        'user' => $user,
        'form' => $form->createView(),
    ));
}

Thanks ahead for your help.

2
  • I think you pasted your UserType class as your "ProduuctType" classes. Can you update your question so we can see your "ProduuctType"? Commented Mar 13, 2017 at 3:25
  • Hello ehymel, thanks for your help. I was passing the right object (user), but wasn't using EntityType. Now it works ;). Commented Mar 14, 2017 at 10:35

1 Answer 1

1

You should use Symfony\Bridge\Doctrine\Form\Type\EntityType instead of CollectionType.

In your UserType

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use AppBundle\Entity\Produit;

public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('nom')
        ->add('prenom')
        ->add('mail')
        ->add('tel1')
        ->add('tel2', TextType::class, array(
            'required' => false
        ))
        ->add('username')
        ->add('password', PasswordType::class)
        ->add('groupe', ChoiceType::class, array(
            'choices' => array(
                'Administrateur' => 'ROLE_SUPER_ADMIN',
                'Gérant' => 'ROLE_ADMIN',
                'Opérateur' => 'ROLE_USER'
            ),
            'expanded' => true,
        ))
        ->add('produits', EntityType::class, array(
            'class' => Produit::class,
            'multiple' => true,
            'expanded' => true,
            'label' => 'nom' //If you don't have a __toString method in your Produit Entity
        ))
    ;
}

/**
 * {@inheritdoc}
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => User::class
    ));
}

/**
 * {@inheritdoc}
 */
public function getBlockPrefix()
{
    return 'gestcoupons_userbundle_user';
}

This way you will have a checkbox for each Product entity in your database and only the one you checked will be associated to your user

Sign up to request clarification or add additional context in comments.

5 Comments

Hello OlivierC, Thanks for your answer ! It was indeed that. I found out yesterday, I still have troubles to get through Symfony documentation ^^. Now I stuck with radio buttons, which I would like to select with user. groupe data. Thanks again !
If you have groupe entities as well you can do just like you did with your products. To get radio button you need to set the expanded to true and the multiple option to false
Also can you mark the question as solved to help others having same troubles in future
Thanks for the answer.. can you provide an example how to set the products that are selected?
By default this code will returned all the entities in your database for the given class. If you want to be more specific about the data you want to be able to fill your form with, you might have a look to the symfony doc about the query_builder option symfony.com/doc/current/reference/forms/types/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.