Skip to content

Instantly share code, notes, and snippets.

@Moinax
Last active August 29, 2015 13:57
Show Gist options
  • Save Moinax/9373783 to your computer and use it in GitHub Desktop.
Save Moinax/9373783 to your computer and use it in GitHub Desktop.
Symfony Form validation through api with common model
<?php
namespace Acme\HelloBundle\Controller;
use Guzzle\Http\Client;
use Guzzle\Http\Exception\BadResponseException;
public function someAction()
{
try {
// instantiate $form here ...
$model = $form->getData(); // get the $model
// convert the $model to a RESTfull $data and send it
$client = new Client();
$request = $client->post('someResource', null, json_encode($data)); // send the data to a RESTfull API
$response = $request->send()->json();
// ...
} catch (ClientErrorResponseException $e) {
if (Response::HTTP_BAD_REQUEST === $e->getResponse()->getStatusCode()) {
$violations = json_decode($e->getResponse()->getBody(true), true);
foreach($violations as $propertyPath => $violation) {
$error = new FormError($this->get('translator')->trans($violation['message'], [], 'validators'), $violation['messageTemplate'], $violation['messageParameters'], $violation['messagePluralization']);
$propertyPath = new PropertyPath($propertyPath);
$field = null; // null or $form->get('aChild') if your property path is in a child
foreach($propertyPath->getElements() as $element) {
$field = $field->get($element);
}
$field->addError($error);
}
}
}
}
<?php
namespace Acme\HelloBundle\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\ConstraintViolation;
public function someAction(Request $request)
{
try {
$data = json_decode($request->getContent(), true);
// convert $data to $model with constraints ...
$validator = $this->get('validator'); // load your validator
$errors = $validator->validate($model); // validate your model
if (count($errors) > 0) {
$violations = [];
/** @var $violation ConstraintViolation */
foreach ($errors as $violation) {
// We get the message template instead of message to avoid translation on this side
$violations[$violation->getPropertyPath()] = ['message' => $violation->getMessageTemplate(), 'messageTemplate' => $violation->getMessageTemplate(), 'messageParameters' => $violation->getMessageParameters(), 'messagePluralization' => $violation->getMessagePluralization()];
}
return new JsonResponse($violations, 400); // return the violations with a 400 status code
}
// your code to persist the model and other stuff to get a transformed $newData
return new JsonResponse($newData, 201); // return the new data withe a 201 status code
} catch (\Exception $e) {
// rollback and other stuff...
return new JsonResponse($e->getMessage(), 500); // return the exception message with a 500 status code
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment