php - easy admin 3 filter AssociationField

I'm struggling to find a solution to filtering the Assocation field list in edit view.
Situation:
User
hasallowedSuppliers
ManyToMany toSupplier
Website
hasenabledSuppliers
ManyToMany toSupplier
Based on the user roles I want to only show a selection ofSupplier
that is in theUser
'sallowedSuppliers
Is it possible to filter these so the user can't see non-allowed optionsenabledSuppliers
Association Field?
Answer
Solution:
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 notROLE_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;
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: can't write image data to path
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.