Symfony Form Select2 Allow user to enter new values

I have a Symfony form in which I have a province field that converts it to Select2. I also want to allow the user to add new values.

 ->add('province', 'entity', array(
                'class' => 'PNC\GeneralBundle\Entity\State',
                'property' => 'name',
                'empty_value'=>'-- Select Province --',
                'label' => ucfirst('State / Province / Region'),
                'required'  => false,
                'attr' => array('class' => 'form-control'),
                'label_attr' => array('class' => 'control-label'),
                'mapped' => false,
            ))

twig

$('#user_profile_type_province').select2({
    tags: "true",
});

controller

if ($request->getMethod() == 'POST') {
 $UserProfileForm->handleRequest($request);
 $province = $UserProfileForm["province"]->getData();
 $tag = $em->getRepository('PNCGeneralBundle:State')->findOneByName($province);
 if(!$tag){
   $newState = new State();
   $newState->setName($province);
   $newState->setCountry($UserProfileForm["country"]->getData());
   $em->persist($newState);
   $em->flush();
   }
}

but I get the value province nullwhen I add a new entry to region select2.

+4
source share
1 answer
0

Source: https://habr.com/ru/post/1621798/


All Articles