【发布时间】:2019-03-22 10:42:53
【问题描述】:
我的表单是标准的,除了提交按钮
{{ form_start(form) }}
{{ form_widget(form) }}
<input type="submit" value="{{ 'action.save'|trans }}" formnovalidate />
{{ form_end(form) }}
我在提交按钮中使用“formnovalidate”禁用了 html5 验证, 因为,例如这里(实体用户)
/**
* @ORM\Column(type="string")
* @Assert\NotBlank(message="assert.notblanc")
* @Assert\Length(
* min = 2, minMessage = "assert.minmessage",
* max = 50, maxMessage = "assert.maxmessage"
* )
*/
private $fullName;
只有一条简单的消息“请匹配请求的格式”(Firefox), 关于长度。不太好。
但是现在,通过“服务器端验证”,我不能像往常一样使用 PHP 类型声明。
public function getFullName(): string
{
return $this->fullName;
}
public function setFullName(string $fullName): void
{
$this->fullName = $fullName;
}
如果提交了一个空的 FullName,我得到一个 symfony 错误
“字符串”类型的预期参数,“NULL”在属性路径“fullName”中给出。
或者添加新用户时的这个
App\Entity\User::getFullName()的返回值必须是string类型,返回null
这个
public function getFullName(): ?string
{
return $this->fullName;
}
public function setFullName(?string $fullName): void
{
$this->fullName = $fullName;
}
解决了这个问题,但这是通常的方式,使一切都“可以为空”吗? 我也想知道......在设置值之后,断言会检查实体值吗?
-- 更新(这里是用户控制器功能)------
/**
* @Route(
* path = "/user-add",
* name = "user_add"
* )
*/
public function addUser(Request $request)
{
$user = new User();
// Update and check user
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Save it
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->addFlash('notice', 'Your changes were saved!');
return $this->redirectToRoute('user_list');
}
return $this->render('user/user_add_update.html.twig', [
'form' => $form->createView()
]);
}
/**
* @Route(
* path = "/user-update/{id<[1-9]\d*>}",
* name = "user_update"
* )
*/
public function updateUser(int $id, Request $request)
{
// Get user
$user = $this->userRepository->find($id);
if (!$user) {
throw $this->createNotFoundException('No user found for id ' . $id);
}
// Update and check user
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Save it
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->addFlash('notice', 'Your changes were saved!');
return $this->redirectToRoute('user_list');
}
return $this->render('user/user_add_update.html.twig', [
'form' => $form->createView(),
]);
}
【问题讨论】: