Setting a default entity value

132 Views Asked by At

I'm trying to set an entity form type to have a default value, i.e the user that is currently logged in.

My code is as follows:

EventType.php

->add('forUser', 'entity', array(
  'label' => 'Staff',
  'class'  => 'BMUserBundle:User'
  'property' => 'fullName',
  'empty_value' => 'Select Staff'.
  'query_builder' => function(EntityRepository $er) {
      return $er->findAllStaff();
  }
))

This works fine and returns all th staff members in the drop down.

I have also tried to do the following:

$form = $this->createForm(new EventType());
$form->get('forUser')->setData("USER_ENTITY") -> entity of logged in user

This doesn't seem to affect the form and it just lists the users with no default selected.

Am I approaching this correctly?

Thanks

1

There are 1 best solutions below

0
On BEST ANSWER

When you instanciate your entity type in the controller, you first have to create a Event object with the user set for the "forUser" relation. Then you just have to pass as 2nd argument your Event object and it will automatically populate the type with.

Here is a small code example to show you how to do :

/src/Your/AppBundle/Controller/YourController.php

    // get the authenticated user
    $user  = $this->get('security.context')->getToken()->getUser();
    $event = new Event();
    $event->setForUser($user);

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

But as forgottenbas said, you have to verify that your EventType has well the data_class option with your Event Classname as value. You'll get more information about it here.

If you let me tell you an off topic advice, you shouldn't use Event as ClassName because the event concept is well too present in Symfony2 development so it'll only obfuscate the code.

Good luck for your project, I hope it'll help you.