我有一個註冊表單,其中包含在用戶實體類中驗證的字段。驗證工作正常,但是我不能返回帶有表單錯誤消息的JsonResponse。JsonResponse中沒有顯示任何表單錯誤 - Symfony
我的登記表控制器的方法是這樣的:
/**
* @Route("/register", name="register")
*/
public function registerAction(Request $request)
{
$user = new User();
$form = $this->createForm(RegistrationType::class, $user);
$form->handleRequest($request);
$errors = "";
if ($form->isSubmitted())
{
if ($form->isValid())
{
$password = $this->get('security.password_encoder')
->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$user->setIsActive(1);
$user->setLastname('none');
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return new JsonResponse(
array(
'message' => 'Success! User registered!',
), 200);
}
else
{
$errors = ($this->get('validator')->validate($form));
return new JsonResponse(
array(
'message' => 'Not registered',
'errors' => $errors,
), 400);
}
}
return $this->render(
'ImmoBundle::Security/register.html.twig',
array('form' => $form->createView(), 'errors' => $errors)
);
}
我得到以下JSON響應,當我提交無效數據登記表:
{"message":"Not registered","errors":{}}
其實我在說「錯誤「:{}將包含一些錯誤字段,但它不包含。有誰知道這裏的問題是什麼?
UPD:
我RegistrationType看起來是這樣的:
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstname', TextType::class)
->add('email', EmailType::class)
->add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat password'),
'invalid_message' => "Passwords don't match!",
))
->add('register', SubmitType::class, array('label' => 'Register'));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'ImmoBundle\Entity\User',
'csrf_protection' => true,
'csrf_field_name' => '_token',
'csrf_token_id' => 'authenticate',
));
}
}
UPD2:找到了解決辦法。我需要做的這個迭代,然後調用的getMessage():
$allErrors = ($this->get('validator')->validate($form));
foreach ($allErrors as $error)
{
$errors[] = $error->getMessage();
}
這並沒有幫助我 – rvaliev
不,同空 「錯誤」:{}。 新增 的foreach($形式 - > getErrors()作爲$錯誤){$ 錯誤[] = $誤差; } – rvaliev
顯示您的RegistrationType代碼 – Dmitry