miholeus

symfony rest api form errors

May 18th, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.09 KB | None | 0 0
  1. <?php
  2.  
  3. namespace ApiBundle\Controller;
  4.  
  5. use ApiBundle\Service\Authenticate;
  6. use FOS\RestBundle\Controller\FOSRestController;
  7. //use FOS\RestBundle\Controller\Annotations\RequestParam;
  8. use FOS\RestBundle\Request\ParamFetcher;
  9. use Symfony\Component\Form\FormInterface;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use TaskBundle\Entity\Project;
  12. use TaskBundle\Entity\User;
  13. use FOS\RestBundle\Controller\Annotations\RequestParam;
  14.  
  15. class ProjectController extends FOSRestController
  16. {
  17.     /**
  18.      *
  19.      * @RequestParam(name="firstname", description="foo")
  20.      *
  21.      * @return \Symfony\Component\HttpFoundation\Response
  22.      */
  23.     public function postProjectsAction(Request $request, ParamFetcher $paramFetcher)
  24.     {
  25.         $form = $this->createForm(\TaskBundle\Form\ProfileType::class, new User());
  26.  
  27.         $this->processForm($request, $paramFetcher, $form);
  28.  
  29.         if (!$form->isValid()) {
  30.             $errors = $this->getErrorsFromForm($form);
  31.             var_dump($errors);
  32.             die;
  33.         }
  34.  
  35.         $data = [
  36.             'random' => random_int(1, 100000)
  37.         ];
  38.  
  39.         $view = $this->view($data);
  40.  
  41.         return $this->handleView($view);
  42.     }
  43.  
  44.     private function processForm(Request $request, ParamFetcher $paramFetcher, FormInterface $form)
  45.     {
  46.         $data = [];
  47.         foreach ($paramFetcher->getParams() as $param) {
  48.             $data[$param->getKey()] = $paramFetcher->get($param->getKey());
  49.         }
  50.  
  51.         $clearMissing = $request->getMethod() != 'PATCH';
  52.         $form->submit($data, $clearMissing);
  53.     }
  54.  
  55.     private function getErrorsFromForm(FormInterface $form)
  56.     {
  57.         $errors = [];
  58.         foreach ($form->getErrors() as $error) {
  59.             $errors[] = $error->getMessage();
  60.         }
  61.  
  62.         foreach ($form->all() as $childForm) {
  63.             if ($childForm instanceof FormInterface) {
  64.                 if ($childErrors = $this->getErrorsFromForm($childForm)) {
  65.                     $errors[$childForm->getName()] = $childErrors;
  66.                 }
  67.             }
  68.         }
  69.  
  70.         return $errors;
  71.     }
  72. }
Add Comment
Please, Sign In to add comment