douxian5963 2017-01-25 12:19
浏览 47
已采纳

Symfony:仅更改EntityType字段的显示关系

I'm having a many-to-many relationship between the tables User and Group. Some of the groups are assigned to the users automatically based on their type. Other groups can be managed by the administrators using the user edit form.

In order to achieve that the administrators can only manage the groups that the are supposed to, I'm using the query_builder option of the EntityType form type.

$builde->add('groups', EntityType::class, [
    // ...
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('g')
                  ->where('g.type = ?1')
                  ->setParameter(1, 'user_managed');
    },
    'multiple' => true,
    // ...
]);

My problem is now that up on saving the user entity only the groups that were selected in the form are associated to the user and that all associations that were not displayed are deleted.

Is there a way to only change the association of the displayed groups to the user instead of all of them?

Thanks

  • 写回答

1条回答 默认 最新

  • dongxianghui3709 2017-01-25 13:35
    关注

    You can use the mapped option in your type in order to not directly map the information in the object :

    $builder->add('groups', EntityType::class, [
        // ...
        'query_builder' => function (EntityRepository $er) {
            return $er->createQueryBuilder('g')
                      ->where('g.type = ?1')
                      ->setParameter(1, 'user_managed');
        },
        'multiple' => true,
        // ...
        'mapped' => false
    ]);
    

    Like that the information doesn't override the group attribute in your object. After the form validation you get the submitted information :

    $groups = $form->get("group")->getData();
    

    And now you can check the difference between the two arrays $user->groups and $groups.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭