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
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
}
}