You are here

public function MailchimpCampaignController::entityAutocomplete in Mailchimp 8

Same name and namespace in other branches
  1. 2.x modules/mailchimp_campaign/src/Controller/MailchimpCampaignController.php \Drupal\mailchimp_campaign\Controller\MailchimpCampaignController::entityAutocomplete()

Callback for entity title autocomplete field.

Parameters

string $entity_type: The entity type to search by title.

Return value

\Symfony\Component\HttpFoundation\JsonResponse A JSON response containing matched entity data.

1 string reference to 'MailchimpCampaignController::entityAutocomplete'
mailchimp_campaign.routing.yml in modules/mailchimp_campaign/mailchimp_campaign.routing.yml
modules/mailchimp_campaign/mailchimp_campaign.routing.yml

File

modules/mailchimp_campaign/src/Controller/MailchimpCampaignController.php, line 367

Class

MailchimpCampaignController
Mailchimp Campaign controller.

Namespace

Drupal\mailchimp_campaign\Controller

Code

public function entityAutocomplete($entity_type) {
  $q = $this->request
    ->get('q');
  $query = $this->entityTypeManager
    ->getStorage($entity_type)
    ->getQuery()
    ->condition('title', $q, 'CONTAINS')
    ->range(0, 10);
  $entity_ids = $query
    ->execute();
  $entities = [];
  if (!empty($entity_ids)) {
    $entities_data = $this->entityTypeManager
      ->getStorage($entity_type)
      ->loadMultiple($entity_ids);
    if (!empty($entities_data)) {

      /* @var $entity \Drupal\Core\Entity\EntityInterface */
      foreach ($entities_data as $id => $entity) {
        $title = $entity
          ->getTypedData()
          ->getString('title');
        $entities[] = [
          'value' => $title . ' [' . $id . ']',
          'label' => Html::escape($title),
        ];
      }
    }
  }
  return new JsonResponse($entities);
}