提问人:Meyo GIT 提问时间:9/11/2023 更新时间:9/12/2023 访问量:64
“请填写此字段”而不是自定义错误消息 |Symfony 5(西姆福尼5号公寓)
"Please fill out this field" instead of custom errors message | Symfony 5
问:
您好,我有一个 Symfony 5 表单,我的字段有约束,我的 Length 约束工作得很好,但 NotBlank 不正确。我有一个“type”和“label”字段,我正在用“type”测试表单和约束,如果我用“type”为空来验证我的表单,它会显示默认的浏览器消息“请填写此字段”,而我希望在我的实体中为“NotBlank”约束定义的自定义消息。
我认为问题是由“required => true”引起的,因为如果我将其更改为“false”并添加“empty_data => '' ”它有效,我可以看到我的自定义消息,但不能完全看到,因为在我的修改表单中,如果我清空“type”字段并验证,它将出现以下消息: “string”类型的预期参数, 在属性路径“type”中给出“null”。
我正在使用Symfony 5,Bootstrap 5,这是我的实体,我的树枝形式和我的FormType.php
实体
/**
* @ORM\Column(type="string", length=255)
* @Assert\Length(
* min = 2,
* max = 50,
* minMessage = "Le type doit faire au minimum {{ limit }} caractères",
* maxMessage = "Le type doit faire au maximum {{ limit }} caractères"
* )
* @Assert\NotBlank(
* message = "Le type est un champ obligatoire"
* )
*/
private $type;
树枝形式
{{ form_start(form) }}
<div class="container-card-global mb-5">
<div class="form-field">
{{form_label(form.type)}}
{{form_errors(form.type)}}
{{form_widget(form.type)}}
</div>
<div class="form-field">
{{form_label(form.description)}}
{{form_widget(form.description)}}
{{form_errors(form.description)}}
</div>
<div class="form-field">
{{form_label(form.statut)}}
{{form_widget(form.statut)}}
</div>
<div class="text-center">
<button class="btn btn-save-global">{{ button_label|default('Valider') }}</button>
</div>
</div>
{{ form_end(form) }}
形式类型:.php
$builder
->add('type', TextType::class, [
'required' => true,
'label' => 'Type',
])
Ty 寻求帮助 !
我看过一些论坛,我尝试使用“novalidate”,但它返回了相同的错误消息,我真的很想保持“required => true”并设法获得我的自定义消息“此字段不能为空”。
答:
您混淆了服务器端错误和前端错误。
当你写的时候,它会把html属性应用到你的输入元素。https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_requiredrequired => true
required
这就是您看到默认浏览器错误的原因。您可以使用 F12 检查输入的 html 标记,如果您想尝试,请删除所需的标记。
然后。如果您设法提交表单(将数据发送到服务器)。Symfony将应用它自己的约束(你的断言)。
这就是为什么您的表单正确显示错误的原因,因为您在表单的每个条目上都使用了此功能。form_errors
但在这种情况下,您看到的错误是从服务器返回的。它们不是浏览器错误。
无论如何,保留对 UX(用户体验)有好处。对于一个完整的用户体验来说,只显示“动态”错误是一件好事。它可以防止用户在知道自己犯了错误之前被迫提交。required => true
但是 Symfony 约束也在这里保护某人可以提交的内容,因此您永远不会注册不完整的数据。你可以把它看作是“中国之墙”。投影项目数据的最后一件事。
评论
required => false
->add('type', TextType::class, [ 'required' => false, 'label' => 'Type', 'constraints' => [new NotBlank(['message' => 'non'])], ])
use Symfony\Component\Validator\Constraints\NotBlank;
对于表单类,您需要添加如下约束: https://symfony.com/doc/current/validation.html#constraints-in-form-classes
评论
->add('type', TextType::class, [ 'required' => false, 'label' => 'Type', 'constraints' => [new NotBlank(['message' => 'non'])], ])
固定 : Il faut aller dans le setter du champ de l'entité et ajouter un ? juste avant le string, on passe simplement de ça :
public function setType(string $type): self
{
$this->type = $type;
return $this;
}
à ca :
public function setType(?string $type): self
{
$this->type = $type;
return $this;
}
评论