2
votes

I'm creating a single-page app with backbone.js and symfony2 and I need your opinion on one thing.

For example see this create user action. The request is sent by a backbone model (model.save), and I want to check values on the server side. My question is pretty simple, is it pertinent to use the symfony2 form validation to do this check ?

/**
 *
 * @Route("/user", defaults={"_format"="json"}, name="create_user")
 * @Method({"POST"})
 */
public function createUserAction() {
    $request = $this->get('request');

    if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
        $data = json_decode($request->getContent(), true);
        $request->request->replace(is_array($data) ? $data : array());
    }

    $entity  = new User();
    $form = $this->createForm(new UserType(), $entity);
    $form->bind($request);
    ... 
}

If yes, how can I do that? Backbone sends JSON request body whereas bind method of Symfony2 form object only accepts URL encoding. I've already tried to use urlencode function without success.

2

2 Answers

0
votes

Yes it is pertinent, you should always do server side validation. My question is where is your content variable coming from? I don't see it being assigned in the above code.

0
votes

You could use FOSRestBundle. It has a "body listener", which will decode request body, and let you bind you form with a request that had a json body.

You can learn more about this feature in the FOSRestBundle documentation.