你好我有一个小问题。我从未在 sf2 中使用过表单验证器,所以我不知道应该从哪里开始。我有一个字段“用户名”,它在数据库中是唯一的,那么我该如何尝试呢?
我的代码:
-> 实体
/**
* @var string $nick_allegro
*
* @ORM\Column(name="nick_allegro", type="string", length=255, unique=true, nullable=true)
*/
private $nick_allegro;
-> 表格
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('nick_allegro')
;
}
public function getDefaultOptions(array $options) {
return array(
'data_class' => 'My\FrontendBundle\Entity\Licence',
);
}
-> Controller
/**
* Displays a form to create a new Licence entity.
*
* @Route("/new", name="licence_new")
* @Template()
*/
public function newAction()
{
$entity = new Licence();
$form = $this->createForm(new LicenceType(), $entity);
return array(
'entity' => $entity,
'form' => $form->createView()
);
}
/**
* Creates a new Licence entity.
*
* @Route("/create", name="licence_create")
* @Method("post")
* @Template("MyFrontendBundle:Licence:new.html.twig")
*/
public function createAction()
{
$entity = new Licence();
$request = $this->getRequest();
$form = $this->createForm(new LicenceType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('licence_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView()
);
}
-> 查看
<form action="{{ path('licence_create') }}" method="post" {{
form_enctype(form) }}>
{{ form_widget(form) }}
<p>
<button type="submit">Create</button>
</p> </form>
最佳答案
您需要使用 Unique Entity在 symfony 中验证模型中的特定字段是唯一的。
为您提供一点帮助(如果您有一个名为 nick
的字段):
1/在您的实体中
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @UniqueEntity("nick")
*/
class User
{
/**
* @var string $email
*
* @ORM\Column(name="nick", type="string", length=255, unique=true)
*/
private $nick;
当您在实体中声明约束时,验证将直接生效。
因此,您已经可以检查 Controller 中的验证。
2/在你的 Controller 中
if ( 'POST' === $request->getMethod()) {
$form->bind($request);
if ($form->isValid())
{
//do something if the form is valid
}
}
关于forms - Symfony 2 Doctrime 2 和表单验证(唯一字段),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12330661/