I\'m creating a REST API controller for Symfony 2. I started using the SensioGeneratorBundle to create a CRUD and modified the controller to act as a REST controller. However, i
To be true, form is not directly related to validation. Let me explain this.
The form component is responsible of mapping data received from the client, be it GET or POST data. So, it will maps string to object of your code (can be an array if not binding to an entity).
Form use the validator component to validate the entity after data have been mapped to it. This means that validation of the entity is totally decoupled from the form component. So, when the form is validated, it really means that the form component validate your entity and not the form data. What gets validated is the entity, not the form.
The form is use solely to take a string representation and map it to the entity hierarchy. The documentation reflects this as the Form and the Validation are distinct sections of the symfony book.
That being said, this also means that the validation of entities can be done outside the form component at great ease. You define you constaints as annotations or in an external file (yml, php or xml) and use the validator component to validate you entity. Here a code example taken from the Validation section of the book:
use Symfony\Component\HttpFoundation\Response;
use Acme\BlogBundle\Entity\Author;
// ...
public function indexAction()
{
$author = new Author();
// ... do something to the $author object
$validator = $this->get('validator');
$errors = $validator->validate($author);
if (count($errors) > 0) {
return new Response(print_r($errors, true));
} else {
return new Response('The author is valid! Yes!');
}
}
As you can see, there is no form involved here, only an object and the validator service. Moreover, the validation component of Symfony2 is completely standalone. This means you can use it without the whole framework. That being said, when used standalone, you loose nice integration with other stuff.
This way, your REST service receives parameters, create entities from it and use the validator service to validate their integrity. Using the form is not mandatory to validate entities.