賞金將在 6 天后到期。此問題的答案有資格獲得 50聲望賞金。 Emilie Tossan正在尋找一個規范的答案:
我將非常感謝您的幫助。
我想了解如何顯示來自表單的錯誤。現在,當我驗證我的專案中的任何表單時,我什么都沒有出現。
如何在 Symfony 中顯示表單錯誤?
謝謝您的幫助。
您可以從以下位置查看我的代碼:
- register.html.twig檔案,其中顯示了我的用戶表單幫助用戶注冊。
- UserController.php檔案,您可以在其中查看驗證用戶表單時發生的情況。
- 還有User.php和UserType.php。
register.html.twig
{% extends 'base.html.twig' %}
{% block title %}Incris-toi !{% endblock %}
{% block main %}
{{ form_start(userform) }}
<div class="alert alert-danger text-center" role="alert">
{{ form_errors(userform.email) }}
{{ form_errors(userform.password) }}
{{ form_errors(userform.gender) }}
{{ form_errors(userform.firstname) }}
{{ form_errors(userform.lastname) }}
{{ form_errors(userform.birthdate) }}
{{ form_errors(userform.occupation) }}
{{ form_errors(userform.nationality) }}
{{ form_errors(userform.nativelanguage) }}
</div>
{{ form_widget(userform.email) }}
{{ form_widget(userform.password) }}
{{ form_widget(userform.gender) }}
{{ form_widget(userform.firstname) }}
{{ form_widget(userform.lastname) }}
{{ form_widget(userform.birthdate) }}
{{ form_widget(userform.occupation) }}
{{ form_widget(userform.nationality) }}
{{ form_widget(userform.nativelanguage) }}
{{ form_widget(userform.save) }}
{{ form_end(userform) }}
用戶控制器.php
<?php
namespace App\Controller\Front;
use App\Entity\User;
use App\Form\UserType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class UserController extends AbstractController
{
#[Route('/register', name: 'register', methods: ['GET', 'POST'])]
public function createUser(
Request $request,
EntityManagerInterface $entityManagerInterface,
UserPasswordHasherInterface $userPasswordHasherInterface
){
$user = new User();
$userform = $this->createForm(UserType::class, $user);
$userform->handleRequest($request);
if ($userform->isSubmitted() && $userform->isValid()) {
$user->setRoles(["ROLE_USER"]);
$plainPassword = $userform->get('password')->getData();
$hashedPassword = $userPasswordHasherInterface->hashPassword($user, $plainPassword);
$user->setPassword($hashedPassword);
$entityManagerInterface->persist($user);
$entityManagerInterface->flush();
return $this->redirectToRoute('home');
}
return $this->renderForm('front/register.html.twig', [
'userform' => $userform,
]);
}
用戶.php
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity(repositoryClass: UserRepository::class)]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 180, unique: true)]
#[Assert\NotBlank]
private ?string $email = null;
#[ORM\Column]
private array $roles = [];
/**
* @var string The hashed password
*/
#[ORM\Column]
#[Assert\NotBlank]
private ?string $password = null;
#[ORM\Column(length: 255)]
#[Assert\NotBlank]
private ?string $gender = null;
#[ORM\Column(length: 255)]
#[Assert\NotBlank]
private ?string $firstname = null;
#[ORM\Column(length: 255)]
#[Assert\NotBlank]
private ?string $lastname = null;
#[ORM\Column(type: Types::DATE_MUTABLE)]
#[Assert\NotBlank]
private ?\DateTimeInterface $birthdate = null;
#[ORM\Column(length: 255)]
#[Assert\NotBlank]
private ?string $occupation = null;
#[ORM\ManyToOne(inversedBy: 'users')]
#[Assert\NotBlank]
private ?Country $nationality = null;
#[ORM\ManyToOne(inversedBy: 'users')]
#[Assert\NotBlank]
private ?Language $nativelanguage = null;
public function __construct()
{
$this->events = new ArrayCollection();
$this->participations = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->email;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* @see PasswordAuthenticatedUserInterface
*/
public function getPassword(): string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getGender(): ?string
{
return $this->gender;
}
public function setGender(string $gender): self
{
$this->gender = $gender;
return $this;
}
public function getFirstname(): ?string
{
return $this->firstname;
}
public function setFirstname(string $firstname): self
{
$this->firstname = $firstname;
return $this;
}
public function getLastname(): ?string
{
return $this->lastname;
}
public function setLastname(string $lastname): self
{
$this->lastname = $lastname;
return $this;
}
public function getBirthdate(): ?\DateTimeInterface
{
return $this->birthdate;
}
public function setBirthdate(?\DateTimeInterface $birthdate): self
{
$this->birthdate = $birthdate;
return $this;
}
public function getOccupation(): ?string
{
return $this->occupation;
}
public function setOccupation(string $occupation): self
{
$this->occupation = $occupation;
return $this;
}
public function getNationality(): ?Country
{
return $this->nationality;
}
public function setNationality(?Country $nationality): self
{
$this->nationality = $nationality;
return $this;
}
public function getNativelanguage(): ?Language
{
return $this->nativelanguage;
}
public function setNativelanguage(?Language $nativelanguage): self
{
$this->nativelanguage = $nativelanguage;
return $this;
}
}
用戶型別.php
<?php
namespace App\Form;
use App\Entity\User;
use App\Entity\Country;
use App\Entity\Language;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\BirthdayType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('gender', ChoiceType::class, [
'choices' => [
'Je suis ...' => '',
'un homme' => 'male',
'une femme' =>'female',
'non-binaire' => 'non-binary'
]
])
->add('lastname')
->add('firstname')
->add('birthdate', BirthdayType::class, [
'placeholder' => [
'year' => 'Année', 'month' => 'Mois', 'day' => 'Jour',
],
'choice_translation_domain' => true
])
->add('occupation')
->add('nationality', EntityType::class, [
'class' => Country::class,
'choice_label' => 'name',
'placeholder' => 'Je choisis un pays'
])
->add('nativelanguage', EntityType::class, [
'class' => Language::class,
'choice_label' => 'name',
'placeholder' => 'Je sélectionne ma langue maternelle'
])
->add('email')
->add('password', PasswordType::class, [
'mapped' => false
])
->add('password', RepeatedType::class, [
'type' => PasswordType::class,
'invalid_message' => 'Les deux mots de passe doivent être identiques.',
'options' => ['attr' => ['class' => 'password-field']],
'required' => true,
'first_options' => ['label' => 'Password'],
'second_options' => ['label' => 'Repeat Password']
])
->add('save', SubmitType::class, [
'attr' => ['class' => 'save'],
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => User::class,
'translation_domain' => 'forms'
]);
}
}
uj5u.com熱心網友回復:
嘗試通過在表單中??僅輸入 2 個字符來測驗最小長度為 3 的“名字”,是否出現表單錯誤?
use Symfony\Component\Validator\Constraints as Assert;
#[ORM\Column(length: 255)]
#[Assert\NotBlank]
#[Assert\Length(min: 3)]
private ?string $firstname = null;
uj5u.com熱心網友回復:
_ 我認為您的 User 類有問題,您沒有為表單設定任何驗證:https ://symfony.com/doc/current/forms.html#validating-forms
驗證是通過向一個類添加一組稱為(驗證)約束的規則來完成的。您可以將它們添加到物體類或表單類。
嘗試向您的班級添加一些規則(#[Assert\NotBlank]),如果不合適,您的表單將拋出錯誤。
_此外,您需要將用戶類(= null)中欄位的默認值洗掉為您需要填充的變數(至少您需要洗掉不能為空的ID)。
_ 在每個欄位的表單中,將“error_bubbling”設定為 true:https ://symfony.com/doc/current/reference/forms/types/text.html#error-bubbling
如果為真,則此欄位的任何錯誤都將傳遞給父欄位或表單。例如,如果在普通欄位上設定為 true,則該欄位的任何錯誤都將附加到主表單,而不是特定欄位。
如果您想控制每個欄位,我認為您需要洗掉此選項,然后 symfony 將在每個欄位上附加錯誤。或者你可以讓這個選項但是你需要更新你的代碼在警報 div 中,而不是呈現每個欄位,而是呈現父欄位或表單。
uj5u.com熱心網友回復:
我正在嘗試找到一種方法來顯示注冊表單中的錯誤。我在我的 User.php 中做到了,但它不起作用......請提出一些建議,以便在電子郵件為空時顯示錯誤。
User.php中的第一個解決方案:
<?php
namespace App\Entity;
#[ORM\Entity(repositoryClass: UserRepository::class)]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Column(length: 180, unique: true)]
#[Assert\NotBlank(message:'test')]
private ?string $email = null;
}
register.html.twig中的第二個解決方案:
{% set formErrors = userform.vars.errors.form.getErrors(true) %}
{% if formErrors|length %}
<ul>
{% for error in formErrors %}
<li>{{ error.message }}</li>
{% endfor %}
</ul>
{% endif %}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/515973.html
標籤:形式交响乐验证
上一篇:無法設定欄位值輸入antdjavascript/reactjs
下一篇:提交后如何呈現表單?
