You are here

public function EntityAutocomplete::buildForm in Examples for Developers 8

Same name and namespace in other branches
  1. 3.x modules/ajax_example/src/Form/EntityAutocomplete.php \Drupal\ajax_example\Form\EntityAutocomplete::buildForm()

Form constructor.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

array The form structure.

Overrides FormInterface::buildForm

File

ajax_example/src/Form/EntityAutocomplete.php, line 70

Class

EntityAutocomplete
A simple autocomplete form which looks up usernames.

Namespace

Drupal\ajax_example\Form

Code

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>',
  ];

  // Here we use the delightful entity_autocomplete form element. It allows us
  // to consistently select entities. See https://www.drupal.org/node/2418529.
  $form['users'] = [
    // A type of entity_autocomplete lets Drupal know it should autocomplete
    // entities.
    '#type' => 'entity_autocomplete',
    // We can specify entity types to autocomplete.
    '#target_type' => 'user',
    // Specifying #tags as TRUE allows for multiple selections, separated by
    // commas.
    '#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;
}