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 them – mostly admins -will get the opportunity to switch categories, but that’s not the problem… for now ^^)
So I first created a relation between the User- and the Category entity. Everything works fine. Each user now has a main category selected.
Only thing which bothers me, is that I cant get hold of the current logged in user in the EntityType (formbuilder) and EntityRepository classes.
In my “New Post” form there are relations to other entities (e.g. Tags). I use the ‘entity’ formtype in the EntityType class to generate these form elements. Now i wan’t to filter the tags, to only allow tags which have the same category relation as the currently logged in users category to be selectable.
I 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.
Now I could filter the tags already in the PostController but the problem is, that I will need this over and over again. And therefore I don’t wan’t to code this everytime I add something new.
I thought it would be the best to place this filter in the EntityRepository. So I can always access the findAllByCategory. But I need the user-object in there.
What is the best way to accomplish this? Have searched a lot, but either I searched for the wrong terms or no one has this problem 🙂
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:Filter tags into your repository: