我在Symfony 4中验证有问题。
我有这样的代码:
这是我的实体类:
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity(repositoryClass="App\Repository\AdminsRepository")
* @UniqueEntity("email")
* @UniqueEntity("login")
*/
class Admins
{
.....
/**
* @ORM\Column(type="boolean")
* @Assert\Type(
* type="integer",
* message="The value {{ value }} is not a valid {{ type }}."
* )
*/
private $type;
public function getId(): ?int
{
return $this->id;
}
...
public function getType(): ?bool
{
return $this->type;
}
public function setType(bool $type): self
{
$this->type = $type;
return $this;
}
}
这是我的Controller类:
...
class AdminController extends AbstractController {
.......
/**
* @Route("/admin/add", name="admin_add")
*/
public function add(Request $request) {
$admins_object = new Admins();
$form = $this->createFormBuilder($admins_object)
->add('first_name', TextType::class, ['label' => 'Imię'])
->add('last_name', TextType::class, ['label' => 'Nazwisko'])
->add('login', TextType::class, ['label' => 'Login'])
->add('email', EmailType::class, ['label' => 'E-mail'])
->add('password', TextType::class, ['label' => 'Hasło'])
->add('type', IntegerType::class, ['label' => 'Typ'])
->add('save', SubmitType::class, ['label' => 'Zapisz'])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($admins_object);
$entityManager->flush();
$this->addFlash(
'notice', 'Dane zostały poprawnie zapisane!'
);
return $this->redirect($request->getUri());
}
return $this->render('admin/add.html.twig', [
'form' => $form->createView()
]);
}
.......
}
和我的观点:
{{ form(form, {'attr': {'novalidate': 'novalidate'}}) }}
当我在'type'字段中放入一些整数(例如'1')时 - 验证器显示消息,如“类型字段不是有效整数...”。
你能帮助我吗?为什么整数验证不起作用?
这是预期的行为,因为TypeValidator
执行的Type
对值执行is_type。
所以类型int
和integer
将使用is_int
执行并返回false,正如您在文档中看到的那样。
见:https://secure.php.net/manual/en/function.is-int.php
工作解决方法将使用IntegerType而不是TextType。