[英]FOSUserBundle Registration Form is invalid but has no error using Symfony 3
我不知道为什么表单在说它不是有效的()但在$ form-> getErrors()上没有错误;
用户注册
/**
* @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
如果跳过验证,则可以创建一个用户,但是在允许注册用户之前,我需要使用FOSUserBundle的默认验证来评估JSON请求。
这是我的json请求的示例
{
"username":"user1",
"fullname":"user1",
"email":"user1@user1.com",
"password":"password"
}
首先,不要忘记将getErrorsFormForm()方法添加到控制器中。 之后,您可以像这样使用它。
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($entityName);
$em->flush();
}
else {
$errors=$this->getErrorsFromForm($form);
}
这就是这种方法;
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.