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.

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

报告相同问题?