Create a Form with Drupal 8 using Form API | Drupal 8

Create a Form with Drupal 8 using Form API

Submitted by editor on Fri, 01/15/2016 - 16:15
Question

How to create a Form, using Form API on Drupal 8 ?

Step 1:  Create a module. (Example)

Step 2 : Configure the info file (Here : test.info.yml) like:
test.form:
  path: '/test-form'
  defaults:
    _title: 'Example form'
    _form: '\Drupal\test\Form\Login'
  requirements:
    _permission: 'access content'

Stem 3 : Create the Form (on your_module/src/Form/Filename.php, Here : test/src/Form/Login.php)
Example:
 

<?php

/**
 * @file
 * Contains \Drupal\test\Form\Login.
 */

namespace Drupal\test\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements an example form.
 */
class Login extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'my_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Your Name'),
    );
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Login'),
      '#button_type' => 'primary',
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if (strlen($form_state->getValue('name')) < 3) {
      $form_state->setErrorByName('name', $this->t('Name error.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('Hello @name', array('@name' => $form_state->getValue('name'))));
  }

}
 

Another example : Entity (user) field with autocomplete function

$currrent_user = \Drupal::currentUser()->id();
$currrent_user = User::load($currrent_user);

$form['uid'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'user',
  '#title' => 'User',
  '#default_value' => $currrent_user,
];

//Settings / Filters : Example, Filter by user role
'#selection_settings' => [
  'filter' => ['role' => ['administrator' => 'administrator']],
],

 

Set Empty value :

'#empty_value' => '',

 

Help : 
https://www.drupal.org/node/2117411
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.