Symfony2 - 为实体字段设置选定的值

时间:2013-04-01 21:21:41

标签: forms symfony entity selected

我正在尝试在实体字段中设置选定的值。根据我在这个主题上看到的许多讨论,我尝试设置data选项,但默认情况下不会选择任何值:

class EventType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('place', 'entity', array(
                'class' => 'RoyalMovePhotoBundle:Place',
                'property' => 'name',
                'empty_value' => "Choisissez un club",
                'mapped' => false,
                'property_path' => false,
                'data' => 2
            ))
            ->add('begin')
            ->add('end')
            ->add('title')
            ->add('description')
        ;
    }

    // ...
}

通过查找更多我发现有些人必须停用映射到实体的表单。这似乎合乎逻辑,所以我试图将'mapped' => false添加到选项中,但没有成功......

如果可以提供帮助,这是我的控制器:

class EventController extends Controller
{
    // ...

    public function addAction()
    {
        $request = $this->getRequest();
        $em = $this->getDoctrine()->getManager();

        $event = new Event();
        $form = $this->createForm(new EventType(), $event);

        $formHandler = new EventHandler($form, $request, $em);

        if($formHandler->process()) {
            $this->get('session')->getFlashBag()->add('success', "L'évènement a bien été ajouté.");
            return $this->redirect($this->generateUrl('photo_event_list'));
        }

        return $this->render('RoyalMovePhotoBundle:Event:add.html.twig', array(
            'form' => $form->createView()
        ));
    }
}

EventHandler类:

class EventHandler extends AbstractHandler
{
    public function process()
    {
        $form = $this->form;
        $request = $this->request;

        if($request->isMethod('POST')) {
            $form->bind($request);

            if($form->isValid()) {
                $this->onSuccess($form->getData());
                return true;
            }
        }

        return false;
    }

    public function onSuccess($entity)
    {
        $em = $this->em;

        $em->persist($entity);
        $em->flush();
    }
}

我现在有点卡住,有没有人有想法?

4 个答案:

答案 0 :(得分:24)

您只需要设置字段的数据:

    
    class EventController extends Controller
    {
        // ...

        public function addAction()
        {
           $request = $this->getRequest();
            $em = $this->getDoctrine()->getManager();

            $event = new Event();
            $form = $this->createForm(new EventType(), $event);

            // -------------------------------------------
            // Suppose you have a place entity..
            $form->get('place')->setData($place);
            // That's all..
            // -------------------------------------------

            $formHandler = new EventHandler($form, $request, $em);

            if($formHandler->process()) {
                $this->get('session')->getFlashBag()->add('success', "L'évènement a bien été ajouté.");
                return $this->redirect($this->generateUrl('photo_event_list'));
            }

            return $this->render('RoyalMovePhotoBundle:Event:add.html.twig', array(
                'form' => $form->createView()
            ));
        }
    }
    

答案 1 :(得分:7)

为了在表单中选择选项,您应该为实体本身设置相应的值。

$place = $repository->find(2);
$entity->setPlace($place);
$form = $this->createForm(new SomeFormType(), $entity);
....

答案 2 :(得分:1)

对于 non-mapped 实体选择字段,我发现最简单的方法是将choice_attr选项与callable一起使用。这将迭代选择集合,允许您根据条件添加自定义属性,并使用扩展,多个和自定义属性选项。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('place', 'entity', array(
            //...
            'choice_attr' => function($place) {
                $attr = [];
                if ($place->getId() === 2) {
                    $attr['selected'] = 'selected';
                    //for expanded use $attr['checked'] = 'checked';
                 }
                 return $attr;
            }
       ))
       //...
    ;
}

答案 3 :(得分:0)

当您使用query_builder选项时,data选项需要一个集合实例,并且希望通过添加{{1}来触摸您的控制器}对于某些字段,并且您已经在表单类型类中拥有了querybuilder和重新填充选项的ID,您可以按以下方式重新填充选择:

setDatas

然后在你的add()方法

// Querybuilder instance with filtered selectable options
$entities = $qb_all; 
// Querybuilder instance filtered by repopulating options (those that must be marked as selected)
$entities_selected = $qb_filtered; 

编辑:真实用例示例

您想重新填充使用以下元素呈现的复选框组:

'data' => $entities_selected->getQuery()->getResult(), // Repopulation 'query_builder' => $entities,

Label: What is your favourite meal?

你想重新填充2个复选框:

4 Checkboxes: Pasta, Pizza, Spaghetti, Steak

Pizza, Steak将是一个包含所有4个可选复选框的QueryBuilder实例

$qb_all将是一个新的附加QueryBuilder实例,其中包含重新填充的复选框$qb_filtered。所以是前一个版本的“过滤”版本。