Doctrine を呼び出す Symfony 2 でカスタムの制約検証を作成します。
if($prevu != 0) {
$total = $prevu + $consomme;
if($total > $charge) {
$this->context->buildViolation($constraint->message1)
->setParameter('%string%', $prevu)
->atPath('intervention.dureeP')
->addViolation();
}
dump($this);
}elseif($realise != 0) {
$total = $realise + $consomme;
if($total > $charge) {
$this->context->buildViolation($constraint->message2)
->setParameter('%string%', $realise)
->atPath('dureeR')
->addViolation();
}
}
私の問題は、エラーがフィールドの横ではなくフォームの上部に表示されることです。
次のような注釈を付けてカスタムバリデーターを呼び出します。
/**
* @var string
*
* @ORM\Column(name="duree_p", type="decimal", precision=3, scale=2, nullable=true)
* @MyAssert\ExceedCharge
*/
private $dureeP;
奇妙なことに、一部のフィールドではその横にエラーが表示されますが、他のフィールドでは上部にエラーが表示されます。
StackOverflow でこの投稿を見たことがあります:カスタム制約検証エラーが Symfony2 のフィールドの隣に表示されませんが、役に立ちませんでした。
オプション「atPath()」を試してみましたが、成功しませんでした。
私が理解していないのは、それがいくつかのフィールドで機能し、私が望むフィールドでは機能しないということです...
誰にも手がかりはありますか?
編集 :
また、違反メッセージが発生したときに、違反メッセージに関連するフィールドに「has-error」クラスがないため、".
編集2:
ここに私の制約ロジックがあります:
class ExceedChargeValidator extends ConstraintValidator
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function validate($value, Constraint $constraint)
{
dump($value); //DEBUG
dump($this->context); //DEBUG
//get id to perform search
$id = $this->context->getObject()->getCast()->getId();
$consomme = $this->em->getRepository('AppBundle:Intervention')->getConsomme($id);
$charge = $this->context->getObject()->getCast()->getCharge();
$prevu = $this->context->getObject()->getDureeP();
$realise = $this->context->getObject()->getDureeR();
dump($prevu); //DEBUG
dump($realise); //DEBUG
if($value != 0) {
$total = $value + $consomme;
if($total > $charge) {
$this->context->buildViolation($constraint->message1)
->setParameter('%string%', $value)
->addViolation();
dump($this->context->getPropertyPath());
}
dump($this); //DEBUG
}
dump($consomme);//DEBUG
dump($charge); //DEBUG
}
}
そして、ここに私のエンティティのいくつかのフィールドがあります:
/**
* @var \DateTime
*
* @ORM\Column(name="date", type="date")
*/
private $date;
/**
* @var string
*
* @ORM\Column(name="duree_p", type="decimal", precision=3, scale=2, nullable=true)
* @MyAssert\ExceedCharge
*/
private $dureeP;
/**
* @var string
*
* @ORM\Column(name="duree_r", type="decimal", precision=3, scale=2, nullable=true)
* @Assert\GreaterThan(
* value = 0
*)
*/
private $dureeR;
フォームは Easy Admin バンドルによって生成されます
同じ制約違反を異なるフィールドに添付すると、次のようになります。私の「日付」フィールドでは問題なく動作することがわかりますが、「dureeP」フィールドではメッセージが上部に表示されます