【发布时间】:2018-09-03 14:45:01
【问题描述】:
想象一下 Symfony 中的示例表单:
public function buildForm(FormBuilderInterface $builder)
{
$builder
->add('email', EmailType::class, [
'constraints' =>
new NotBlank(),
new IsUnique(),
],
])
->add('password', PasswordType::class, [
'constraints' =>
new NotBlank(),
new IsStrongEnough(),
],
])
}
现在,当我提交表单并确保它有效时,我希望 $form->getData() 返回我的 DTO,名为 CreateAccountCommand:
final class CreateAccountCommand
{
private $email;
private $password;
public function __construct(string $email, string $password)
{
$this->email = $email;
$this->password = $password;
}
public function getEmail(): string
{
return $this->email;
}
public function getPassword(): string
{
return $this->password;
}
}
示例控制器:
$form = $this->formFactory->create(CreateAccountForm::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->commandBus->dispatch($form->getData());
return new JsonResponse([]);
}
我不能通过data_class 直接使用这个类,因为表单显然希望模型具有允许空值的设置器。表单本身运行良好,验证也是如此。
我尝试使用Data mapper 方法,但在验证之前调用了mapFormsToData 方法。
这可能吗?还是我应该将数据作为数组获取并在表单之外创建对象?
【问题讨论】:
-
在模型中,某些字段(例如电子邮件)可以为空,但您希望它们在表单中是强制性的吗?
-
我已经更新了我的问题。
-
->add('email', EmailType::class, array('required' => true)) -
required => true只是一个 html5 验证(无论如何它都是默认值),不知道你为什么写这个。就像我在问题中所说,验证部分工作正常。 -
这样,您可以覆盖模型可为空的字段来验证表单。我不得不以相反的方式使用该技巧,我的模型中有不可为空的属性,我不得不使用
'required' => false来强制验证
标签: php symfony symfony-forms symfony4