0

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

0

The core autocomplete feature expects the label of the returned matches contain the id of the referenced entity like Superuser (8) which is parsed by the drupal.autocomplete behavior and submitted through the actual form input. The easy solution its to ensure that your response returns the expected values. But you can always implement your own. See Drupal\entity_reference\EntityReferenceController to see how the core implenents it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.