Symfony Form Select2允许用户输入新值


Symfony Form Select2 Allow User to Enter New Values

我有一个Symfony Form,其中有一个字段Province,它将其转换为Select2。我想允许用户也允许新的值。

 ->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,
            ))

树枝

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

控制器

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();
   }
}

但当我在省select2中新输入时,我得到了CCD_ 1值CCD_。

它按预期工作:)您没有实体,因此存在null。为了让它发挥作用,你必须制作一个DataTransformer(http://symfony.com/doc/current/cookbook/form/data_transformers.html)在那里,如果状态不存在,您将获取该状态,并创建一个新的实体对象。请确保级联正确,这样新状态将与用户配置文件一起持久化。