0

I can't find out why the form are saying that it is not valid() but the are no errors on $form->getErrors();

UserRegistration

/**
 * @ApiDoc(
 *     description="Register User, NEEDS TO ADD MORE INFORMATION HERE",
 *     statusCodes={
 *         400 = "Validation failed."
 *     }
 *  )
 */
public function registerAction(Request $request)
{

    /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
    $formFactory = $this->get('fos_user.registration.form.factory');
    /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
    $userManager = $this->get('fos_user.user_manager');
    /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
    $dispatcher = $this->get('event_dispatcher');

    $data = $request->request->all();
    $user = $userManager->createUser();
    $user->setUsername($data['username']);
    $user->setUsernameCanonical($data['username']);
    $user->setFullName($data['fullname']);
    $user->setEmail($data['email']);
    $user->setEmailCanonical($data['email']);
    $user->setPlainPassword($data['password']);
    $user->setEnabled(true);


    $event = new GetResponseUserEvent($user, $request);
    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

    if (null !== $event->getResponse()) {
        return $event->getResponse();
    }

    $form = $formFactory->createForm();
    $form->setData($user);


    if ( ! $form->isValid()) {

        // this won't return error
        $errors = $this->getErrorsFromForm($form);

        $event = new FormEvent($form, $request);
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);

        if (null !== $response = $event->getResponse()) {
            return $response;
        }
        $errors = $form->getErrors(true);;

        return new JsonResponse(['errors' => $errors], Response::HTTP_BAD_REQUEST);
    }

    $event = new FormEvent($form, $request);
    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);

    if ($event->getResponse()) {
        return $event->getResponse();
    }

    $userManager->updateUser($user);

    $response = new JsonResponse(
        [
            'msg' => $this->get('translator')->trans('registration.flash.user_created', [], 'FOSUserBundle'),
            'token' => $this->get('lexik_jwt_authentication.jwt_manager')->create($user), // creates JWT
        ],
        Response::HTTP_CREATED,
        [
            'Location' => $this->generateUrl(
                'get_profile',
                [ 'user' => $user->getId() ],
                UrlGeneratorInterface::ABSOLUTE_URL
            )
        ]
    );

    $dispatcher->dispatch(
        FOSUserEvents::REGISTRATION_COMPLETED,
        new FilterUserResponseEvent($user, $request, $response)
    );

    return $response;
}

UserEntity

<?php

namespace AppBundle\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use JMS\Serializer\Annotation as JMSSerializer;
use AppBundle\Model\ProjectInterface;


use FOS\UserBundle\Model\User as BaseUser;
/**
 * @ORM\Entity
 *
 * @ApiResource
 * @UniqueEntity("email")
 * @UniqueEntity("username")
 */
class User extends BaseUser 
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=false)
     * @Assert\NotBlank()
     * @Groups({"user"})
     */
    protected $fullname;

    /** @ORM\ManyToOne(targetEntity="Project", inversedBy="user") */
    private $projects;

    /** @ORM\Column(type="datetime") */
    private $created_at;

    /** @ORM\Column(type="float") */
    private $balance;

    /** @ORM\Column(type="string", nullable=true) */
    private $stripe_id;

    public function __construct()
    {
        parent::__construct();
        // your own logic
        $this->roles = array('ROLE_USER');
        $this->created_at = new \DateTime();
        $this->balance = 0.00;
        $this->stripe_id = NULL;
    }

   // setter and getter removed

I can create a user if I skipped the validation, but I need to evaluate the JSON request using FOSUserBundle's default validation before allowing to register a user.

Here is an example of my json request

{
    "username":"user1",
    "fullname":"user1",
    "email":"user1@user1.com",
    "password":"password"
}
almar.io
  • 21
  • 3
  • can you dump $errors = $this->getErrorsFromForm($form); outside the if ( ! $form->isValid()) { – famas23 May 13 '17 at 21:50
  • try to add $form->submit($user); before $form->isValid() – ghaziksibi May 14 '17 at 00:41
  • See this: https://stackoverflow.com/questions/13006932/display-all-errors-with-form-errorsform-plus-for-each-field-in-symfony2/45609448#comment84359439_45609448 – Superbiji Feb 08 '18 at 08:54

1 Answers1

0

Firstly do not forget the add getErrorsFormForm() method to your controller. After you can use it like this.

if ($form->isSubmitted() && $form->isValid()) {
    $em->persist($entityName);
    $em->flush();
}
else {
    $errors=$this->getErrorsFromForm($form);
}

Here is that method;

private function getErrorsFromForm(FormInterface $form)
{
    $errors = array();
    foreach ($form->getErrors() as $error) {
        $errors[] = $error->getMessage();
    }
    foreach ($form->all() as $childForm) {
        if ($childForm instanceof FormInterface) {
            if ($childErrors = $this->getErrorsFromForm($childForm)) {
                $errors[$childForm->getName()] = $childErrors;
            }
        }
    }
    return $errors;
}
Mehmet S.
  • 394
  • 3
  • 18