gpt4 book ai didi

php - Symfony - 在字段约束类中获取实体对象

转载 作者:行者123 更新时间:2023-12-04 02:04:58 25 4
gpt4 key购买 nike

我创建了自定义约束验证器:

class CustomConstraint extends Constraint
{
public $message = '';
}

class CustomConstraintValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
exit($this->context->getObject()); // returns null
}
}

docs据称:

Returns the currently validated object.

,但对我而言,它返回 NULL

附言我不想将此约束分配给实体,只分配给某些表单或字段。

已验证的表单属性:

->add('rejectReasons', null, array(
'property' => 'name',
'multiple' => true,
'constraints' => array(
new CustomConstraint(array(
'message' => 'Application can not be refused.'
)),
)
));

实体中的属性:

/**
* @ORM\ManyToMany(targetEntity="RejectReason")
* @ORM\JoinTable(name="relationship_application_reject_reasons",
* joinColumns={@ORM\JoinColumn(name="application_id", referencedColumnName="id", onDelete="CASCADE")},
* inverseJoinColumns={@ORM\JoinColumn(name="reject_reason_id", referencedColumnName="id")}
* )
*/
private $rejectReasons;

更新

我尝试对其他字符串属性施加约束,我仍然得到 NULL

最佳答案

ExecutionContextInterface它说:

getObject() Returns the currently validated object.

If the validator is currently validating a class constraint, the object of that class is returned. If it is a validating a property or getter constraint, the object that the property/getter belongs to is returned.

In other cases, null is returned.

如您所见,您必须分配给类或属性或 getter。否则你将得到 null

关于php - Symfony - 在字段约束类中获取实体对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44177742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com