首页 > 解决方案 > Symfony 验证在没有表单的情况下获取旧值

问题描述

在我们的项目中,我们有多个可翻译的实体(使用 DoctrineBehaviors 中的 Translatable)。我们的用户拥有(或没有)语言的权利,如果用户没有语言的权利,则不应更新该字段。

作为更好的解释,我得到了 2 个实体(没有完全写出来,但很重要):

+------------------------+
| TranslationKey         |
+------------------------+
| id INT                 |
| translationKey STRING  |
| translations COLLECTION|
+------------------------+

+------------------------+
| TranslationContent     |
+------------------------+
| id INT                 |
| translation STRING     |
| locale STRING          |
+------------------------+

基本上,每个用户都有一种或多种语言,如果区域设置在用户语言的缩写数组中,则用户可以编辑该语言的翻译。

但是,如果没有表单(例如,如果我们将开始使用 API 请求),仍应验证实体。我的想法是:创建一个自定义验证并检查该字段是否被编辑(当该字段未被编辑时,它不应该失败),如果是:检查权限,并抛出错误或恢复原始值。

我得到了这个示例路线(只是测试路线,不会在生产中使用):

/**
 * @Route("tuet/{translationKey}", name="tuet")
 */
public function testUpdateEnglishTranslation(TranslationKey $translationKey, ObjectManager $em, ValidatorInterface $validator) {
    $translationKey->setTranslation('en', 'products2', $validator);

    $validator->validate($translationKey);
    return $this->render('base.html.twig');
}

我添加了如下所示的验证类:

class CanEditEnglishLanguageValidator extends ConstraintValidator {
    private $em;

    public function __construct(EntityManagerInterface $em) {
        $this->em = $em;
    }

    public function validate($object, Constraint $constraint) {
        dd($this->em->getRepository(get_class($object))->find(1)->getTranslation('en'));
    }
}

然而,出于某种原因——可能是因为实体对象缓存在 Doctrine 中——dd 将显示翻译而不是旧翻译,但是新翻译在object. 如何获得旧值?

标签: phpsymfonydoctrineconstraints

解决方案


推荐阅读