Я сделал регистрационную форму согласно этому документу
Как реализовать простую регистрационную форму
Работает хорошо, но в случае ошибки ничего не возвращает и просто перезагружается.
Например.
+ Использовать уже существующее имя пользователя.
+ Неправильная двойная проверка пароля.
Я хочу показать сообщение в этих случаях.
Как я могу поймать сообщение об ошибке ???
Кстати, что касается входа в систему
Я могу поймать такую ошибку в контроллере безопасности
class SecurityController extends AbstractController
{
/**
* @Route("/login", name = "app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
// get the login error here
$this->data['error'] = $authenticationUtils->getLastAuthenticationError();
то я хочу также поймать ошибку в контроллере регистрации
<?php
namespace App\Controller;
use App\Form\UserType;
use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use App\Service\CommonFunc;
class RegistrationController extends AbstractController
{
/**
* @Route("/register", name = "user_registration")
*/
public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder,CommonFunc $commonFunc)
{
$this->data['user'] = $this->getUser();
// 1) build the form
$user = new User();
$form = $this->createForm(UserType::class, $user);
$this->data['error'] = $authenticationUtils->getLastAuthenticationError();
// 2) handle the submit (will only happen on POST)
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// 3) Encode the password (you could also do this via Doctrine listener)
$password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
// 4) save the User!
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
// ... do any other work - like sending them an email, etc
// maybe set a "flash" success message for the user
return $this->redirectToRoute('index');
}else if ($form->isSubmitted()) {
print $form->getErrors();exit; //nothing returns here.
}
$this->data = array_merge($this->data,$commonFunc->makeMenuBar());
$this->data['noLoginForm'] = true;
return $this->render(
'registration/register.html.twig',
array('form' => $form->createView(),'data' => $this->data)
);
}
}
В моем случае как-то form->getErrors() ничего не возвращает else if ($form->isSubmitted()) { print $form->getErrors();exit; //nothing returns here. } , я обновил код




попробуйте заменить form_row на form_widget или добавить form_error в шаблон веточки
подробнее см. Справочник по функциям и переменным шаблонов Twig (Документы Symfony)
{# templates/registration/register.html.twig #}
{{ form_start(form) }}
{{ form_widget(form.username) }}
{{ form_widget(form.email) }}
{{ form_widget(form.plainPassword.first) }}
{{ form_widget(form.plainPassword.second) }}
<button type = "submit">Register!</button>
{{ form_end(form) }}
Кажется, вам нужно искать ошибки проверки, если
$form->isValid()- этоfalse. Попробуй отладить, что в$form->getErrors(). Но ваша форма должна отображать его на входе, если произошли какие-то ошибки. Вы можете получать сообщения об ошибках нравится