-->

Form bind not binding request to form in Symfony 2

2019-08-04 09:33发布

问题:

I'm implementing rest API using FOSRestbundle. Now say for POST request i'm getting request parameters properly like:

Symfony\Component\HttpFoundation\ParameterBag Object
(
    [parameters:protected] => Array
        (
            [rank] => 12
            [city] => 1345
            [comment]=> 'safd'
        )

)

My post action code is :

/**
 * @Rest\View
 */   
public function newAction(){

    $rank= new Rank();       
    $form = $this->createForm(new RankType(), $rank);
    $form->bind($this->getRequest());
    if ($form->isValid()) {
      //.  $user->flush();

      $em = $this->getDoctrine()->getManager();
      $em->persist($rank);
      $em->flush();
      $response = new Response();
      $response->setStatusCode($statusCode);
      $view = View::create()  
        ->setData($rank)
        ->setFormat('json');

      return $this->handleView($view);
    }

    return $this->handleView(View::create($form, 400));
}

But form->isValid fails due to setting null values to form.

After Binding form form->getData() will display :


MyProject\DataBundle\Entity\Rank Object
(
    [city:MyProject\DataBundle\Entity\Ranking:private] => 
    [rank:MyProject\DataBundle\Entity\Ranking:private] => 
    [comment:MyProject\DataBundle\Entity\Ranking:private] => 
)   

RankType code :

class RankType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('rank');
        $builder->add('city');
        $builder->add('comment');
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class'        => 'Myporject\DataBundle\Entity\rank',
            'csrf_protection'   => false,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'rank';
    }
}

Validation will throw error like city and rank should not be null

Any suggestions why $form->bind not binding values?

回答1:

I think, that I've just resolved the same problem in my app :)

Look at your form: getName() method returns 'rank' - and this is the name of the form AND this is the namespace for this form data :) Symfony2 will use it to bind.

So, when you will send data like that:

array('rank'=> 'somevalue', 'city' => 'comecityname', 'comment' => 'somecomment')

it will not work, because bind method will search for array of data placed under 'rank' namespace and will find string 'somevalue'. Form data will remain empty.

Change format of data to that:

array('rank' => array('rank'=> 'somevalue', 'city' => 'comecityname', 'comment' => 'somecomment'))

and send it with REST - then it should work

I hope this will help