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
tried to use the query_builder option from the entity formtype. But as i can't get the current user object, i don't know which category he has selected. Same problem with the EntityRepository.
As long the Category has a relation to the user, you should be able to get the User there.
For Example:
Controller
$someThing = new SomeThing();
$someThing->setUser($user);
$form = $this->createForm(new someThingType(), $someThing);
Form
$someThing = $options['data'];
$user = $someThing->getUser();
$builder->add('category', null, array(
'class' => 'MyBundle:Cateogry',
'query_builder' =>
function(EntityRepository $er) use ($user) {
return $er->getCategoriesForUser($user);
}
));
Repository
public function getCategoriesForUser($user)
{
$qb = $this->createQueryBuilder('c');
$qb->leftJoin('c.user', 'u', 'with', 'u.user = :user');
$qb->setParameter('user', $user)
;
return $qb;
}
this is not exactly your use-case but pretty similar to it. maybe it helps you.
You can get user object from Security Context
$user = $serviceContainer->get('security.context')->getToken()->getUser();
Small tip: In case if user is not logged in - you'll have string in $user
, otherwise - User object.
Cheers ;)
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
}
}