我有一个表格,其中为产品添加了参考编号。我使此字段唯一,因为不会有重复的参考编号。
我遇到的问题是,当我添加已附加到另一个产品的参考编号时,我遇到了异常Integrity constraint violation: 1062 Duplicate entry for key 'reference'
。相反,我希望表单向用户显示一条消息,以通知他们引用已在使用中。
编辑:我创建了一个自定义验证器来检查给定的引用是否已经存在,但是我收到以下错误:
Type error: Too few arguments to function BackendModulesGlassesDomainGlassesValidatorConstraintsDuplicateReferenceValidator::__construct(), 0 passed in /var/www/html/vendor/symfony/symfony/src/Symfony/Component/Validator/ContainerConstraintValidatorFactory.php on line 52 and exactly 1 expected
我似乎无法在DuplicateReferenceValidator
中得到我的GlassesRepository
数据传输对象:
<?php
namespace BackendModulesGlassesDomainGlasses;
use BackendModulesGlassesDomainBrandBrand;
use BackendModulesMediaLibraryDomainMediaGroupMediaGroup;
use CommonDoctrineEntityMeta;
use SymfonyComponentValidatorConstraints as Assert;
use BackendModulesGlassesDomainGlassesValidatorConstraints as CustomAssert;
class GlassesDataTransferObject
{
/*** Other fields ***/
/**
* @var string
*
* @AssertNotBlank(message="err.FieldIsRequired")
* @CustomAssertDuplicateReference
*/
public $reference;
/*** Other fields ***/
重复引用.php
<?php
namespace BackendModulesGlassesDomainGlassesValidatorConstraints;
use SymfonyComponentValidatorConstraint;
/**
* @Annotation
*/
class DuplicateReference extends Constraint
{
public $message = '"{{ reference }}" already exists.';
}
DuplicateReferenceValidator.php
<?php
namespace BackendModulesGlassesDomainGlassesValidatorConstraints;
use BackendModulesGlassesDomainGlassesGlassesRepository;
use SymfonyComponentValidatorConstraint;
use SymfonyComponentValidatorConstraintValidator;
use SymfonyComponentValidatorExceptionUnexpectedTypeException;
class DuplicateReferenceValidator extends ConstraintValidator
{
private $repository;
/**
* DuplicateUserValidator constructor.
*/
public function __construct(GlassesRepository $repository)
{
$this->repository = $repository;
}
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof DuplicateReference) {
throw new UnexpectedTypeException($constraint, DuplicateReference::class);
}
// custom constraints should ignore null and empty values to allow
// other constraints (NotBlank, NotNull, etc.) take care of that
if (null === $value || '' === $value) {
return;
}
if (!is_string($value)) {
// throw this exception if your validator cannot handle the passed type so that it can be marked as invalid
throw new UnexpectedTypeException($value, 'string');
}
$qb = $this->repository->createQueryBuilder('g');
$qb->select('g.reference')
->where('g.reference = :reference')
->setParameter('reference', $value);
$match = $qb->getQuery()->execute();
if ($match) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ reference }}', $value)
->addViolation();
}
}
}
我自己想通了。
我需要将实体管理器添加到我的services.yml
文件中,以便能够在验证器中访问它。
BackendModulesGlassesDomainGlassesValidatorConstraintsDuplicateReferenceValidator:
attributes:
- "@doctrine.orm.entity_manager"