Access currently logged in user in EntityRepository

后端 未结 3 2089
北恋
北恋 2020-12-11 12:16

I want to create a simple blog example where users have a favourite category attached to there account. This means the can only write articles for this category. (Some of th

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-11 12:57

    You can inject security context in your form type defined as a service. Then in your tags field use the query builder with $user (current logged user) to filter tags which have the same category relation as the currently logged:

    /** @DI\Service("form.type.post") */
    class PostType extends \Symfony\Component\Form\AbstractType
    {
        /**
         * @var \Symfony\Component\Security\Core\SecurityContext
         */
        protected $securityContext;
    
        /**
         * @DI\InjectParams({"securityContext" = @DI\Inject("security.context")})
         *
         * @param \Symfony\Component\Security\Core\SecurityContext $context
         */
        public function __construct(SecurityContext $securityContext)
        {
            $this->securityContext = $securityContext;
        }
    
        public function buildForm(FormBuilder $builder, array $options)
        {
            $user = $this->securityContext()->getToken()->getUser();
    
            $builder->add('tags', 'entity', array(
                'label'         => 'Tags',
                'class'         => 'Acme\HelloBundle\Entity\Tag',
                'property'      => 'name',
                'query_builder' => function(EntityRepository $er) use($user) {
                    return $er->getAllSuitableForUserChoiceQueryBuilder($user);
                },
                'multiple'      => true,
                'expanded'      => true,
        }
    }
    

    Filter tags into your repository:

    class TagRepository extends EntityRepository
    {
        public function getAllSuitableForUserChoiceQueryBuilder(User $user)
        {
            // Filter tags that can be selected by a given user
        }
    }
    

提交回复
热议问题