【发布时间】:2014-07-29 03:14:45
【问题描述】:
也许这是一个热门话题,其他一些人谈论这个,但我还没有找到解决这个问题的好方法。以UNIQUE 字段的此错误为例。当我尝试将相同的值插入数据库时,我收到此错误:
SQLSTATE[23000]:违反完整性约束:1062 重复条目 键“UNIQ_FC3A5A1592FC23A8”的“j1234567”
当然,这发生在app_dev.php (development) 环境中,但我不知道如何处理这个问题,以便向用户显示错误页面而不是这个丑陋的错误。我在production 测试了相同的代码,然后丑陋的错误消失了,但我得到了这个:
错误:内部服务器错误
不过,路径不止一个,例如,我可以在插入之前或通过 AJAX 发送请求之前检查记录的存在,但我想学习如何通过使用 Symfony2 和 Doctrine2 断言来实现这一点。我已经将此代码添加到我的实体中:
<?php
....
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* SysPerfil
*
* @ORM\Entity
* @ORM\Table(name="sys_perfil")
* @UniqueEntity(fields={"rif"}, message="Este RIF ya existe en nuestra base de datos")
* @UniqueEntity(fields={"ci"}, message="Este CI ya existe en nuestra base de datos")
* @UniqueEntity(fields={"nombre"}, message="Este nombre ya existe en nuestra base de datos")
*/
class SysPerfil
{
....
但由于我收到上述错误,它无法正常工作,那么处理此问题的最佳方法是什么?有任何想法吗?建议?文档?
添加表单类型
是的,我通过表单类型发送数据,见下文:
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
->add('email', 'email', array(
'required' => true,
'label' => 'Email',
'trim' => true
))
->add('password', 'password', array(
'required' => true,
'label' => 'Contraseña',
'always_empty' => true
))
->add('confirm', 'password', array(
'required' => true,
'mapped' => false,
'label' => 'Verificar contraseña',
'always_empty' => true
))
->add('enabled', 'checkbox', array(
'required' => true,
'label' => 'Activo?',
'data' => true
))
->add('perfil', new AdminPerfilType());
}
还有AdminPerfilType.php:
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
->add('persJuridica', 'choice', array(
'choices' => RifType::getChoices(),
'required' => true,
'label' => 'RIF',
'trim' => true,
'attr' => array(
'class' => 'persJuridica'
)
))
->add('roleType', 'choice', array(
'choices' => AdminRoleType::getChoices(),
'required' => true,
'label' => "Tipo de Usuario",
'trim' => true
))
->add('rif', 'text', array(
'required' => true,
'label' => false,
'trim' => true,
'attr' => array(
'class' => "numeric",
'maxlength' => 15
)
))
->add('ci', 'text', array(
'label' => 'CI',
'trim' => true,
'attr' => array(
'class' => "numeric ci",
'disabled' => 'disabled'
)
))
->add('nombre', 'text', array(
'required' => true,
'label' => 'Nombre',
'trim' => true
))
->add('apellido', 'text', array(
'required' => true,
'label' => 'Apellidos',
'trim' => true
));
}
如果您正在表单中寻找验证规则,那么我没有,因为我虽然 Doctrine/Symfony2 已经处理了该部分
【问题讨论】:
-
您可以创建自己的constraints validator
-
@tttony 我喜欢那个,但是我如何从约束中访问实体管理器以检查数据库中是否已经存在该值?
-
您是否使用表单插入实体?你能显示更多代码吗?
-
@ra_htial 根据您的要求添加了额外信息
-
@ReynierPM here 是如何使用约束验证器的更好示例,但我认为最好使用 UniqueEntity()
标签: php symfony exception exception-handling doctrine-orm