Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 - Set a selected value for the entity field

I'm trying to set a selected value inside an entity field. In accordance with many discussions I've seen about this topic, I tried to set the data option but this doesn't select any of the values by default:

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

    // ...
}

By looking for more I've found that some people had to deactivate the form mapping to the entity. That seems logical so I tried to add 'mapped' => false to the options, without success...

If it can help, here's my controller:

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

And the EventHandler class:

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

I'm a bit stuck right now, is there anyone who got an idea?

like image 206
Nesk Avatar asked Apr 01 '13 21:04

Nesk


3 Answers

You only need set the data of your field:

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

like image 104
Andy.Diaz Avatar answered Oct 22 '22 19:10

Andy.Diaz


In order to option appear selected in the form, you should set corresponding value to entity itself.

$place = $repository->find(2);
$entity->setPlace($place);
$form = $this->createForm(new SomeFormType(), $entity);
....
like image 28
gatisl Avatar answered Oct 22 '22 17:10

gatisl


For non-mapped entity choice fields, the method I found easiest was using the choice_attr option with a callable. This will iterate over the collection of choices and allow you to add custom attributes based on your conditions and works with expanded, multiple, and custom attribute options.

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;
            }
       ))
       //...
    ;
}
like image 1
Will B. Avatar answered Oct 22 '22 17:10

Will B.