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
Comments