I have a form with this field. the user can save one or more results. I want to filter by the foreign key who is on the user table but i don’t know how to do this.
My code :
$form['referent_business'] = [ '#title' => 'Référent', '#type' => 'entity_autocomplete', '#target_type' => 'user', '#required' => TRUE, '#tags' => TRUE, '#validate_reference ' => TRUE, '#autocreate' => false ]
So I tried another solution :
$form['referent_business'] = [ '#title' => 'Référent', '#type' => 'textfield', '#autocomplete_route_name' => 'jds.autocomplete_referent_ce', '#autocomplete_route_parameters' => [ 'business' => $entity->id() ], '#required' => TRUE, '#tags' => TRUE, '#validate_reference ' => TRUE, '#autocreate' => false, '#access' => $user->hasRole('administrator') ? TRUE : FALSE, ];
With the function
public function autocompleteReferentCE(Request $request, $business) { $matches = []; if($string = $request->query->get('q')) { $query = Drupal::entityQuery('user') ->condition('status', 1) ->condition('id_business', $business) ->condition('last_name', '%'.db_like($string).'%', 'LIKE'); $idUsers = $query->execute(); $users = User::loadMultiple($idUsers); foreach($users as $user) { $matches[] = [ 'value' => $user->get('first_name')->value . ' ' . $user->get('last_name')->value, 'label' => $user->get('first_name')->value . ' ' . $user->get('last_name')->value ]; } } return new JsonResponse($matches); }
The custom entity_autocomplete function works. When the user saves several results, the return isn’t an array, but a string.
So, someone knows how to filter with the first solution or return an array of result with the second solution ? Or another solution ?
Thanks in advance