如何在symfony的表单组件中限制输入字段中的数字(1-10)?
How to put the limit on number (1-10) in input field in form component of symfony?
我使用 symfony 表单组件为表单编写了一些代码,但我需要将级别输入字段中的数字限制为 1-10。因此,如果它更低或更高,它必须抛出错误或警报。有什么方法可以帮助实现这一目标吗?
$form = $this->createFormBuilder($skill)
->add('name', TextType::class, array('attr' => array(
'required' => true,
'class' => 'form-control')))
->add('level', NumberType::class, array(
'required' => true,
'attr' => array('class' => 'form-control')
))
->add('save', SubmitType::class, array(
'label' => 'Create',
'attr' => array('class' => 'btn btn-primary mt-3')
))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$skill = $form->getData();
$entityManager = $this->getDoctrine()->getManager();
$person = $entityManager->getRepository(Person::class)->find($person_id);
$person->addSkill($skill);
$entityManager->persist($skill);
$entityManager->persist($person);
$entityManager->flush();
return $this->redirectToRoute('skill_list');
}
return $this->render('main/new.html.twig', array(
'form' => $form->createView()
));
当您将数字输入到实体中时,您可以对实体本身使用相当标准的断言。 Range.
<?php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Skill
{
// .. other fields
/**
* @ORM\Column(type="integer")
* @Assert\Range(
* min = 1,
* max = 10,
* minMessage = "You must rate at least {{ limit }} points",
* maxMessage = "You cannot rate yourself higher than {{ limit }} points"
* )
*/
protected $level;
}
表单的 isValid()
将使用这些注释来检查 $level 的有效范围,并且 return 显示给定数字不是从 1 到 10 的错误。
我使用 symfony 表单组件为表单编写了一些代码,但我需要将级别输入字段中的数字限制为 1-10。因此,如果它更低或更高,它必须抛出错误或警报。有什么方法可以帮助实现这一目标吗?
$form = $this->createFormBuilder($skill)
->add('name', TextType::class, array('attr' => array(
'required' => true,
'class' => 'form-control')))
->add('level', NumberType::class, array(
'required' => true,
'attr' => array('class' => 'form-control')
))
->add('save', SubmitType::class, array(
'label' => 'Create',
'attr' => array('class' => 'btn btn-primary mt-3')
))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$skill = $form->getData();
$entityManager = $this->getDoctrine()->getManager();
$person = $entityManager->getRepository(Person::class)->find($person_id);
$person->addSkill($skill);
$entityManager->persist($skill);
$entityManager->persist($person);
$entityManager->flush();
return $this->redirectToRoute('skill_list');
}
return $this->render('main/new.html.twig', array(
'form' => $form->createView()
));
当您将数字输入到实体中时,您可以对实体本身使用相当标准的断言。 Range.
<?php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Skill
{
// .. other fields
/**
* @ORM\Column(type="integer")
* @Assert\Range(
* min = 1,
* max = 10,
* minMessage = "You must rate at least {{ limit }} points",
* maxMessage = "You cannot rate yourself higher than {{ limit }} points"
* )
*/
protected $level;
}
表单的 isValid()
将使用这些注释来检查 $level 的有效范围,并且 return 显示给定数字不是从 1 到 10 的错误。