-1

I'm struggling to find a solution to filtering the Assocation field list in edit view.

Situation:

  • User has allowedSuppliers ManyToMany to Supplier
  • Website has enabledSuppliers ManyToMany to Supplier

Based on the user roles I want to only show a selection of Supplier that is in the User's allowedSuppliers

Is it possible to filter these so the user can't see non-allowed optionsenabledSuppliers Association Field?

1 Answers1

2

This can be done by changing the choices via setFormTypeOptions on the Field in configureFields. I've put an example below that checks if user roles is not ROLE_ADMIN if not it will only show the allowed choices, this seems to work just the way I want it to.

Took a bit of guesswork and digging since this wasn't clearly explained in the docs.

public function configureFields(string $pageName): iterable
{
    $fields = [];
    if (array_search('ROLE_ADMIN', $this->getUser()->getRoles()) === false) {
        /** @var User|null $user */
        $user = $this->entityManager->getRepository(User::class)->findOneBy([
            'username' => $this->getUser()->getUsername()
        ]);
        if ($user) {
            $fields[] = AssociationField::new('suppliers')->onlyOnForms()->setFormTypeOptions([
                "choices" => $user->getEnabledSuppliers()->toArray()
            ]);
        }
    } else {
        $fields[] = AssociationField::new('suppliers')->onlyOnForms();
    }
    return $fields;
}
  • can you tell me how you have implemented the `enitityManager`-Property? I tried this with injection via the constructor, but the constructor in not called on my CrudContoller. – Tim K. Dec 09 '20 at 08:02
  • You want to use the [entityManagerInterface](https://stackoverflow.com/questions/49618780/how-to-inject-doctrine-entity-manager-into-symfony-4-service) – Max van der Sluis Dec 18 '20 at 15:42