Creating a simple form in Drupal 8

posted in: Drupal | 0

Forms are generated as classes in Drupal 8. Each form has its own class for building, validating and handling submitted value. This is awesome because it allows easy grouping of form related functions in a single class.

Also in the routing management we can give route to the class where form is built, validated and handles submitted values. Following is an example of simple route to a form.

lnformcontrol.myform:
    path: 'lnformcontrol/myform'
    defaults: 
        _form: Drupal\lnformcontrol\Form\MyForm
        _title: 'This is my form'
    requirements:
        _permission: 'access content'

When we go to the path lnformcontrol/myform it will be managed by the class Drupal\lnformcontrol\Form\MyForm.

Now create folder Form under modulename/src folder and create the class MyForm. It should extend the class FormBase and also it uses FormStateInterface to hold the values that are input.  The form should implement these three methods to make it usable.

  • getFormId()
  • buildForm()
  • submitForm()
namespace Drupal\lnformcontrol\Form;

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

class MyForm extends FormBase {

    public function getFormId() {
        return 'lnformcontrol_myform';
    }

    public function buildForm(array $form, FormStateInterface $form_state) {

        $form['name'] = array(
            '#type' => 'textfield',
            '#title' => $this->t("Enter Your Name"),
            '#size' => 50,
            '#maxlength' => 50,
            '#description' => $this->t("Enter your name to check the value"),
        );

        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => $this->t("submit"),
        );

        return $form;
    }

    public function submitForm(array &$form, FormStateInterface $form_state) {
        $name = $form_state->getValue('name');
        drupal_set_message($this->t("You have entered name :%name", array('%name' => $name)));
    }

}

 

For more information we can check Form API in Drupal

Leave a Reply