4
votes

I have a Symfony Form in which I have a field of Province, that convert it into Select2. I want to allow user to allow new values also.

 ->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 am getting province value null when I new input in province select2.

1
Make special form type for itMax P.
What does you meant by Special Type?Muhammad Taqi

1 Answers

0
votes

It's working as expected :) you don't have the entity so there is null. To make it work you will have to make an DataTransformer (http://symfony.com/doc/current/cookbook/form/data_transformers.html) and there you will fetch the state if it does not exist you create a new entity object. Be sure to have cascades right so the new state will be persisted with user profile.