Micha
Micha

Reputation: 43

Symfony2.3 - pass variables from controller to formtype and back

I want to pass a variable from controller to formtype and back to controller. I tried to realize the topics about passing data from controller and passing values but I get the error

ContextErrorException: Notice: Undefined variable: id in C:\xampp\htdocs\pso\src\Pso\ProjectBundle\Form\ProjectuserType.php line 38

and I can't see, where my mistake is. I think I defined the variable. Therefore I would be glad for a hint, what I didn't see.

Controller:

$form =  $this->createForm(new ProjectuserType($id));

Formtype:

class ProjectuserType extends AbstractType
{

private $id;

public function __construct($id)
{
    $this->id = $id;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{

$id = $this->id;

$builder->addEventListener(
        FormEvents::PRE_SET_DATA,
        function (FormEvent $event) {
            $form = $event->getForm();

            $formOptions = array(
                'class' => 'Pso\LogBundle\Entity\User',
                'property' => 'username',
                'multiple' => 'true',
                'expanded' => 'true',
//Line 38
                'query_builder' => function (EntityRepository $er) use($id)  {
                     return $er->createQueryBuilder('x')->FROM('PsoLogBundle:user', 'u');
                },
            );

            $form->add('user', 'entity', $formOptions)
                 ->add('Submit', 'submit', array(
            'attr'=> array (
                'formnovalidate' => 'formnovalidate'
            )
        ));
        }
    );
}

After submitting the form, I want to pass the variable back to controller.

My goal with all that is, that I have the form, which represents all users, that are actually not related to the representated object. For that I want to pass the id for the representated object to the form. When I activate a checkbox in the form and submitting it, I want to create an entry in db to relate the user to the object with the id.

Upvotes: 0

Views: 248

Answers (1)

Alexandru Furculita
Alexandru Furculita

Reputation: 1373

You need to add one more use ($id):

...
$builder->addEventListener(
    FormEvents::PRE_SET_DATA,
    function (FormEvent $event) use ($id) {
    ....

Upvotes: 1

Related Questions