Symfony Assert\Expression 比较实体属性与当前用户属性。

huangapple go评论55阅读模式
英文:

Symfony Assert\Expression compare entity property with current users property

问题

你能否在Symfony的Assert\Expression中获取当前已验证的用户对象?

我想要使用类似以下的方式:

#[Assert\Expression(
    this.getType() != user.getType(),
    message: 'Invalid type'
)]

我尝试了但遇到错误:

Variable "user" is not valid around position 60 for expression
英文:

Is it possible to get current authenticated user object in symfony Assert\Expression ?

I want to use something like

#[Assert\Expression(
    this.getType() != user.getType()",
    message: 'Invalid type'
)]

I tried but getting an error

Variable \"user\" is not valid around position 60 for expression

答案1

得分: 1

我不认为直接从你的实体中获取当前经过身份验证的用户是可能的。

在这种情况下,你应该按照这里解释的方式创建一个自定义约束和验证器:https://symfony.com/doc/current/validation/custom_constraint.html#creating-the-constraint-class。

你可以创建一个HasValidTypeHasValidTypeValidator,在其中你可以注入Symfony的Security组件并执行$this->security->getUser()以获取当前经过身份验证的用户。

英文:

I don't think it is possible to get the current authenticated user directly from your entity.

In this case, you should create a custom constraint & validator as explained here : https://symfony.com/doc/current/validation/custom_constraint.html#creating-the-constraint-class.

You could create a HasValidType and HasValidTypeValidator in which you can inject the Security component of Symfony and perform a $this->security->getUser() to get the current authenticated user.

huangapple
  • 本文由 发表于 2023年4月17日 15:21:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76032586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定