1

I have two entities (User and Project), with generated CRUD options. Relation between entities is OneToMany bidirectional (user 1 - * project). In project/new, CRUD generated drop-down list for Users, but I want to set logged User automatically, without picking it from drop-down list.

Here is ProjectType/buildForm() function:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('projectTitle')
        ->add('user')
    ;
}

Can I set logged User as Project creator in buildForm() (from session?, database?), or somewhere else? Thanks.

ddtr
  • 45
  • 5
  • That's not a valid Symfony2 code (incomplete field definitions in builder). What have you tried? You can have user as an entity field and then build form passing proper object as that field value. – Tomasz Kowalczyk Dec 17 '14 at 11:52
  • 2
    @TomaszKowalczyk It is valid, it will guess the type, which works for strings and numbers and such. – Marcel Burkhard Dec 17 '14 at 11:53

2 Answers2

5

Yes in your Controller you probably have something like this:

$entity = new Project();

$form   = $this->createEditForm($entity);

You can add the following line inbetween the lines above:

$entity->setUser($this->get('security.context')->getToken()->getUser());

Then your user is preselected in the form.

If you want to hide it you can use $form->remove('user'); and set the user like mentioned in createAction and updateAction after $form->handleRequest($request);

Marcel Burkhard
  • 3,453
  • 1
  • 29
  • 35
0

You can retrieve your user object in controller and send it as form parameter:

$form = $this->createForm(new CustomFormType($user), $entity);

class CustomFormType extends AbstractType
{
    protected $user;

    public function __construct($user) {
        $this->user = $user;
    }
}
Cristian Bujoreanu
  • 1,147
  • 10
  • 21