0

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.

1 Answer 1

1

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

...
$builder->addEventListener(
    FormEvents::PRE_SET_DATA,
    function (FormEvent $event) use ($id) {
    ....
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.