这里继续窥探 symfony/form
的用法, 来了解一下 Form 的 Validator.
通常在项目开发中, 框架自带的表单验证器可以满足硬性指标, 但是业务验证部分就无能为力了. 需要工程师自行开发适合项目的表单验证规则.
比如在用户系统中, 用户的邮件地址我们需要进行唯一性验证, 已经被注册的邮件地址不能重复注册, 那么我们就需要开发一个 EmailUniqueValidator
来添加到 Form 的 email 字段中的验证器中去.
继续使用 make:validator
指令, 创建一个验证器: EmailUniqueValidator
$ bin/console make:validator
The name of the validator class (e.g. EnabledValidator):
> EmailUniqueValidator
created: src/Validator/EmailUniqueValidator.php
created: src/Validator/EmailUnique.php
Success!
Next: Open your new constraint & validators and add your logic.
修改 src/Validator/EmailUnique.php
因为我们需要传入数据库查询管理器和配置错误信息.
接下来实现正式的验证器代码, 修改 src/Validator/EmailUniqueValidator.php
emailInUsed($value, $constraint->manager->getRepository(User::class))) {
$this->context->buildViolation($constraint->message)->addViolation();
}
}
/**
* 检测邮件地址是否已经存在数据库中.
*
* @param string $email
* @param UserRepository $userRepository
* @return bool
*/
private function emailInUsed(string $email, UserRepository $userRepository): bool
{
//根据邮件地址查询数据库
$user = $userRepository->findOneBy(['email' => $email]);
if ($user instanceof User) {
return true;
}
return false;
}
}
接下来就剩下在 UserType 这个 Form 类中添加这个邮件地址验证器: EmailUnique
, 再传入数据库管理器这个对象: Doctrine\Common\Persistence\ObjectManager
.
ObjectManager
对象传入到 Form 类中通常可以通过创建是通过参数传递, 也可以把 Form 类定义为 Service 来使用, 通过注入传递这个 ObjectManager
.
通过参数来传递到 UserType
add('email', EmailType::class, [
'empty_data' => '',
'constraints' => [
new NotBlank(['message' => 'Emaill address cannot be empty.']),
new Email(['message' => 'This email is not a valid email address.']),
new EmailUnique([
'manager' => $entityManager, // manager 与 EmailUniqueValidator 的 manager属性保持同名.
]),
]
])
->add('passwd', PasswordType::class, [
'empty_data' => '',
'constraints' => [
new NotBlank(['message' => 'Password cannot be empty character.']),
new Length([
'min' => 4,
'max' => 12,
'minMessage' => 'Your password must be at least {{ limit }} characters long',
'maxMessage' => 'Your password cannot be longer than {{ limit }} characters',
])
]
])
->add('name', TextType::class, [
'empty_data' => '',
'constraints' => [
new NotBlank(['message' => 'Your name cannot be empty.']),
new Length([
'min' => 2,
'max' => 12,
'minMessage' => 'Your name must be at least {{ limit }} characters long',
'maxMessage' => 'Your name cannot be longer than {{ limit }} characters',
])
]
])
->add('save', SubmitType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
//表单创建时需要提供实体管理器参数
$resolver->setRequired('entity_manager');
}
}
在 Controller 中传入 ObjectManager
:
// ...
public function signUp(Request $request)
{
//创建用户注册表单对象
$form = $this->createForm(UserType::class, null, [
'entity_manager' => $this->getDoctrine()->getManager(),
]);
//监听表单请求
$form->handleRequest($request);
// ...
这样邮件唯一性验证就完成了.
如果修改 Controller
里的代码, 把 UserType 定义成 Service, 也可以实现参数的注入.
修改 src/Form/UserType.php
entityManager = $entityManager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', EmailType::class, [
'empty_data' => '',
'constraints' => [
new NotBlank(['message' => 'Emaill address cannot be empty.']),
new Email(['message' => 'This email is not a valid email address.']),
new EmailUnique([
'manager' => $this->entityManager, // manager 与 EmailUniqueValidator 的 manager属性保持同名.
]),
]
])
->add('passwd', PasswordType::class, [
'empty_data' => '',
'constraints' => [
new NotBlank(['message' => 'Password cannot be empty character.']),
new Length([
'min' => 4,
'max' => 12,
'minMessage' => 'Your password must be at least {{ limit }} characters long',
'maxMessage' => 'Your password cannot be longer than {{ limit }} characters',
])
]
])
->add('name', TextType::class, [
'empty_data' => '',
'constraints' => [
new NotBlank(['message' => 'Your name cannot be empty.']),
new Length([
'min' => 2,
'max' => 12,
'minMessage' => 'Your name must be at least {{ limit }} characters long',
'maxMessage' => 'Your name cannot be longer than {{ limit }} characters',
])
]
])
->add('save', SubmitType::class)
;
}
}
把 Controller 里的代码复原:
//...
//创建用户注册表单对象
$form = $this->createForm(UserType::class);
//监听表单请求
$form->handleRequest($request);
//...
如此, 也实现了与上面同样的功能. 这里由于使用了 autowire 功能. 不需要手动注册 Service. 如果未启动, 需要手动修改一下 config/service.yaml
添加一下声明:
services:
App\Form\UserType:
arguments: ['@doctrine.orm.entity_manager']
tags: [form.type]
到此, 简单的自定义 Valiadator
就完成了.