英文:
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。
你可以创建一个HasValidType
和HasValidTypeValidator
,在其中你可以注入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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论