[英]Symfony2 + Doctrine2: Is it possible to interact with validation annotations within an Entity setter?
I have an Entity which i have decorated using validation annotations like this: 我有一个使用验证注释修饰过的实体 ,如下所示:
use Symfony\Component\Validator\Constraints as Assert;
class Entity
{
/**
* @Assert\MaxLength(100)
*/
protected $property;
...
}
Within the setter for $property
i want to know if validation was successful of the annotation when a form is submitted. 在
$property
的设置器中,我想知道提交表单时批注的验证是否成功。 If validation is successful (or not) i will perform other operations in PHP that is not available via the annotations. 如果验证成功(或失败),我将在PHP中执行其他无法通过注释进行的操作。
Is this possible? 这可能吗? ie:
即:
...
function setProperty($value)
{
if(annotation_validation_passed_when_form_submitted)
{
$value = do_something($value);
}
$this->property = $value;
}
...
You can add an EventListener
to your FormBuilder
to listen for the FormEvents::BIND
event. 您可以将
EventListener
添加到FormBuilder
以侦听FormEvents::BIND
事件。 You can either do this in its own class or just in the form builder itself. 您可以在其自己的类中执行此操作,也可以仅在表单构建器中执行此操作。 I'll show an example of the latter because it's faster.
我将展示后者的示例,因为它更快。
$builder->addEventListener(FormEvents::BIND, function($event) {
$data = $event->getData();
$comment = $data->getComment();
$comment = $comment . $comment;
$data->setComment($comment);
});
Of course replace the logic with your own. 当然用您自己的逻辑代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.