Skip to content

Instantly share code, notes, and snippets.

@onema
Last active December 20, 2015 03:08
Show Gist options
  • Save onema/6060893 to your computer and use it in GitHub Desktop.
Save onema/6060893 to your computer and use it in GitHub Desktop.
Get form errors. Symfony 2.3
<?php
namespace Acme\DemoBundle\Controller;
//...
class ApiController extends Controller
{
//...
public function processForm(Request $request)
{
// ...
$form = $this->createForm($documentType, $document, array('method' => $request->getMethod()));
$form->handleRequest($this->getRequest());
if($form->isValid()) {
// Save Data
}
else {
$errors = $this->getErrorMessages($form);
return $errors;
}
return $response;
}
private function getErrorMessages(\Symfony\Component\Form\Form $form) {
$errors = array();
foreach ($form->getErrors() as $key => $error) {
$errors[$key] = $error->getMessage();
}
if ($form->count()) {
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$errors[$child->getName()] = $this->getErrorMessages($child);
}
}
}
return $errors;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment