我遵循了以下Symfony2 cookbook tutorial,但我一直收到错误
constraint myContraintClass cannot be put on properties or getters
在validation.yml我有
Core\Entity\Activity:
properties:
maxTotalParticipant:
- Application\ActivityBundle\Validator\ActivityMaxTotalParticipant: ~
这是我的约束
<?php
namespace Application\ActivityBundle\Validator;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class ActivityMaxTotalParticipant extends Constraint
{
public $message = 'trigger error';
public function validatedBy() {
return 'activity_max_total_participant_validator';
}
public function getTargets() {
return self::CLASS_CONSTRAINT;
}
public function getMessage() {
return $this->message;
}
}
和我的约束验证器
<?php
namespace Application\ActivityBundle\Validator;
use Symfony\Component\Validator\ExecutionContext;
use Symfony\Bundle\DoctrineBundle\Registry;
use myApp\Core\Entity\Activity;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation;
class ActivityMaxTotalParticipantValidator extends ConstraintValidator
{
private $doctrine;
private $translator;
public function __construct(Registry $doctrine, Translator $translator){
$this->doctrine = $doctrine;
$this->translator = $translator;
}
/**
* @param : $value {Activity object}
* @param : $constraint {ActivityMaxTotalParticipant object}
* */
public function isValid( $value, Constraint $constraint) {
if($value->getId() !== null) { return true; }
return false;
}
private function isMaxTotalParticipantGreaterThanActualParticipants(Activity $activity, ExecutionContext $context){
$activityUser = $this->doctrine->getEntityManagerForClass('myApp\Core\Entity\ActivityUser')->getRepository('myApp\Core\Entity\ActivityUser')->countNumberParticipantByActivityId($value->getId());
if($activityUser > $activity->getMaxTotalParticipant() && $activity->getMaxTotalParticipant() !== null) {
$propertyPath = $this->context->getPropertyPath().'.maxTotalParticipant';
$this->context->setPropertyPath($propertyPath);
$this->context->addViolation($constraint->message, array(), null);
return false;
}
return true;
}
private function isMaxTotalParticipantGreaterEqualOne(Activity $activity, ExecutionContext $context)
{
$maxTotalParticipant = $activity->getMaxTotalParticipant();
if ($activity->getNumberOfPlacesLimited() == 1 && ($maxTotalParticipant == null || trim($maxTotalParticipant) == '' || $maxTotalParticipant < 1) ) {
return false;
}
return true;
}
}
答案 0 :(得分:18)
您应该将getTargets()
的返回值更改为self::PROPERTY_CONSTRAINT
。现在它是self::CLASS_CONSTRAINT
,这意味着约束只能放在类级别,而不能放在属性级别(例如你的属性$maxTotalParticipant
)。