I have an entity called Question
which has a Many to Many relationship with another entity User
. So I have following tables:
question(id, field1, users)
user(id, name)
question_user(question_id, user_id)
I use EasyAdmin for creating QuestionCrud form where I use AssociationField
for assigning multiple Users to a Question. If I use AssociationField
without autocomplete()
method it works like a charm and stores the data. But I have really big amount of data in User table and that's why need to use autocomplete in order to load only small amount of data.
Using autocomplete()
with AssociationField
giving following error and giving validation error on a form submit:
The choices 123, 2323 do not exist in the choice list.
123, 2323 are IDs of the selected users.
Has anybody faced such a problem?
A month ago another developer faced the same problem - https://github.com/EasyCorp/EasyAdminBundle/issues/5467. He proposed to edit vendor file src/Form/EventListener/CrudAutocompleteSubscriber.php
and thanks to his investigation on what was wrong with autocomplete() method on many-to-many relationship we came out with another solution.
Instead of editing a vendor file we decided to override findBy
method of the Entity repository.
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
{
if (isset($criteria['id']) && is_array($criteria['id'])) {
$ids = [];
foreach ($criteria['id'] as $id) {
if (Uuid::isValid($id)) {
$ids[] = Uuid::fromString($id)->toBinary();
} else {
$ids[] = $id;
}
}
$criteria['id'] = $ids;
}
return parent::findBy($criteria, $orderBy, $limit, $offset);
}
This solution is good as far as you have only one Entity which is used as many-to-many relationship, but if there are several entities, then the findBy
method should be overridden in all of them.
Hope that supporters of EasyAdmin will fix this bug soon and we will not need to use such 'ugly' solutions.