I have users who are venue managers. I want them to be able to manage their places and events that are happening in these places.
I created fos_user_user and there I built relations to places:
<entity name="Application\Sonata\UserBundle\Entity\User" table="fos_user_user">
<id name="id" column="id" type="integer">
<generator strategy="AUTO" />
</id>
<many-to-many field="places" target-entity="EchoBundle\Entity\Place">
<join-table name="users_places">
<join-columns>
<join-column name="user_id" referenced-column-name="id" />
</join-columns>
<inverse-join-columns>
<join-column name="place_id" referenced-column-name="id" />
</inverse-join-columns>
</join-table>
</many-to-many>
</entity>
So now, I can manage users and add places that they manage. It works fine.
Questions:
How can I filter so once they log in they only see their own places?
How can I allow them to only add events to their own places? Currently when you add an event you have a full list of places to select from.
How can I filter all events so that they only see events related to places they manage?
I looked at "CUSTOMIZING THE QUERY USED TO GENERATE THE LIST" in the Sonata documentation but don't know how to use it. I tried to add security queries found in answers on StackOverflow from 4 years ago but it didn't work.
In your Admin class you can override createQuery
(you should check and fix example below to meet your app model) ;)
This solution will cover question 1 and 3.
public function createQuery($context = 'list')
{
$query = parent::createQuery($context);
$aliases = $query->getRootAliases();
$query
->leftJoin($aliases[0] . '.users_places', 'users_places')
->andWhere($query->expr()->eq('users_places.user_id', ':user') )
->setParameter('user', $this->getConfigurationPool()->getContainer()->get('security.token_storage')->getToken()->getUser());
return $query;
}
Question 2:
If you are using sonata formMapper
and configureFormFields
method, you can pass Custom Query Builder in field definition.
$formMapper
->add('events', 'sonata_type_model', [
'label' => 'Events',
'placeholder' => 'Select ...',
'required' => true,
'query' => $blQueryBuilder,
]);