EntityAutocomplete.php in Examples for Developers 3.x
File
modules/ajax_example/src/Form/EntityAutocomplete.php
View source
<?php
namespace Drupal\ajax_example\Form;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
class EntityAutocomplete implements FormInterface, ContainerInjectionInterface {
use StringTranslationTrait;
use MessengerTrait;
protected $entityTypeManager;
public static function create(ContainerInterface $container) {
$form = new static($container
->get('entity_type.manager'));
$form
->setStringTranslation($container
->get('string_translation'));
$form
->setMessenger($container
->get('messenger'));
return $form;
}
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
public function getFormId() {
return 'ajax_example_autocomplete_user';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['info'] = [
'#markup' => '<div>' . $this
->t("This example uses the <code>entity_autocomplete</code> form element to select users. You'll need a few users on your system for it to make sense.") . '</div>',
];
$form['users'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'user',
'#tags' => TRUE,
'#title' => $this
->t('Choose a user (Separate with commas)'),
];
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Submit'),
];
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
$state_users = $form_state
->getValue('users');
if (empty($state_users)) {
$form_state
->setErrorByName('users', 'There were no users selected.');
}
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$state_users = $form_state
->getValue('users');
$users = [];
foreach ($state_users as $state_user) {
$uid = $state_user['target_id'];
$users[] = $this->entityTypeManager
->getStorage('user')
->load($uid)
->getDisplayName();
}
$this
->messenger()
->addMessage('These are your users: ' . implode(' ', $users));
}
}