Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Create a Form with Drupal 8 using Form API

By editor , 15 January, 2016
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']],
],

And for a taxonomy:
$form['term'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'taxonomy_term',
  '#title' => 'Taxo',
  '#selection_settings' => [
    'target_bundles' => ['tags'],
  ],
]

Set Empty value :

'#empty_value' => '',

 

Multiple selection

Example: Multiple selection using select and multiple option.
 $form['list'] = [
   '#type' => 'select',
   '#title' => 'List',
   '#options' => ['a', 'b', 'c'],
   '#multiple' => TRUE,
 ];

Example: Multiple selection using checkboxes.
$form['list'] = [
   '#type' => 'checkboxes',
   '#title' => 'List',
   '#options' => ['a', 'b', 'c'],
 ];

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

Tags

  • Drupal 8
  • Code
  • Module
  • Form
  • Drupal 9
Create a simple module for Drupal 8 - Step 2 - Create Simple Page
Tips for Form API of Drupal 8
Autocomplete function for textfield of Form API
Increment or Decrement number of Fields Dynamically using Form API and Ajax
Add a Form in to a Basic Controller
CKEditor inline image files usage for custom forms.

Comments

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer