TAGS :Viewed: 9 - Published at: a few seconds ago

[ Symfony2: Form:bind data ]

I've got simple form

    $transformer = new ModuleToArrayTransformer($this->entityManager);
    $builder->add('modules', 'collection', array(
        'type' => 'checkbox',
        'required' => false,
        'data' => $options['data'][0]->getModules(),
    ))
    ->add('save', 'submit', array(
        'label' => 'btn_update_and_edit_again',
        'attr' => array(
            'class' => 'btn btn-primary'
        )
    ))
    ->addViewTransformer($transformer);

And controller for it:

 $em = $this->getDoctrine()->getManager();
    $user = $this->get('security.context')->getToken()->getUser();

    $module = $em->getRepository('AcmeProjectBundle:Module')
        ->findBy(
            array(
                'user' => $userId,
                'project' => $projectId,
            )
        );

    if (!$module) {
        $module = $this->createAction($projectId, $userId);
    }

    $userData = $em->getRepository('AcmeSonataUserBundle:User')->find($userId);
    $projectData = $em->getRepository('AcmeProjectBundle:Project')->find($projectId);
    $form = $this->createForm(new ModuleType($em), $module, array('user' => $userData, 'project' => $projectData));
    if ($request->getMethod() == 'GET') {
        if ($form->isValid()) {
        }

    }
    return $this->render('AcmeProjectBundle:Module:edit.html.twig', 
        array(
            'form' => $form->createView(),
            'projectId' => $projectId,
            'userId' => $userId,
        )
    );

The form is connected with another form. When I click on checkbox in the first form this form is generated - correctly. Until I try to $form->bind($request);

When I try to bind request it is showing sth like "This value is incorrect"

The $_GET seems to be fine

array (size=1)
  'acme_projectbundle_module' => 
array (size=2)
  'modules' => 
    array (size=8)
      'stats' => string '1' (length=1) 
      'time' => string '1' (length=1) 
      'issues' => string '1' (length=1) 
      'metrics' => string '1' (length=1) 
      'timeLine' => string '1' (length=1) 
      'information' => string '1' (length=1) 
      'status' => string '1' (length=1) 
      'risks' => string '1' (length=1) 
  'save' => string '' (length=0) 

as well as the $request variable

If form looks exactly like my $_GET request what's the problem? As far as I know $_GET should contain the same values as $request->parameters field. How is is supposed to look like then? Where is the problem?

Answer 1


You are trying to bind the form and check isValid when the request method is GET i.e. in the case when you just want to display the form to the user. And in that case you are bound to get the error

"This value is incorrect"

because the $request does not contain any values.

So you should bind the form only when the data is submitted and not when the form is being displayed.