How can you contact us

2By phone at +40 749 014 360

If you still have problems, please let us know, by sending an email to info@westweb-solutions.com Thank you!

OFFICE HOURS

Mon-Fri 9:00AM - 6:00AM
Sat - 9:00AM - 1:00PM
Sundays by appointment only!

Drupal 8 - How to replace drupal_get_form()

/ / Drupal 8

In this tutorial I will show you how to create a simple form using Drupal 8.

In order to create a new form, we need to extend the FormBase class. The FormBase class is implementing the FormInterface interface, so our class needs to implement the methods from FormInterface.

The place where we create forms in Drupal 8 is: /mymodule/src/Form

The class name should end in 'Form', for example: ExampleForm.

The methods from FormInterface are:


interface FormInterface {

  /**
   * Returns a unique string identifying the form.
   *
   * @return string
   *   The unique string identifying the form.
   */
  public function getFormId();

  /**
   * Form constructor.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The form structure.
   */
  public function buildForm(array $form, FormStateInterface $form_state);

  /**
   * Form validation handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function validateForm(array &$form, FormStateInterface $form_state);

  /**
   * Form submission handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state);
}


So, our form needs to implement all of these methods.

Create a new class ExampleForm and place it in /mymodule/src/Form/ExampleForm.php.

Method getFormID() should return the ID of the form. In Drupal 7, the ID was the name of function that was returning the form. This is not the case anymore in Drupal 8.

Second method that we need to implement from FormInterface is: buildForm. This is similar with Drupal 7 function and it needs to return an array containing the form elements.


  // Drupal 8
  public function getFormId() {
    return 'example_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Name'),
    );

    $form['phone'] = array(
      '#type' => 'tel',
      '#title' => $this->t('Your phone number'),
    );

    // Define the buttons.
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );

    return $form;
  }

  // Drupal 7 equivalent
  function example_form($form, &$form_state) {
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Name'),
    );

    $form['phone'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Your phone number'),
    );

    // Define the buttons.
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
    );

    return $form;
  }


The Drupal 7 functions formname_validate(&$form, &$form_state) and formname_submit(&$form, &$form_state) are replaced in Drupal 8 with:

public function validateForm(array &$form, FormStateInterface $form_state)

and

public function submitForm(array &$form, FormStateInterface $form_state)

In these functions, we add our custom code for validation of the form and also for submit.

In the validateForm() method, we can use setErrorByName() to raise a validation error.


  // Drupal 8
  public function validateForm(array &$form, FormStateInterface $form_state) {   
    $form_state->setErrorByName('phone_number', $this->t('Error with phone number'));
  }

  // Drupal 7 equivalent is:
  function example_form_validate(&$form, &$form_state) {   
    form_set_error('phone_number', t('Error with phone number'));  
  }


In the submitForm() method we can process the form values.



  // Drupal 8
  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t("Hi %name, your phone number is %phone.", array(
      '%name' => $form_state->getValue('name'),
      '%phone' => $form_state->getValue('phone'),
    )));
  }


  // Drupal 7 equivalent:
  function example_form_submit(&$form, &$form_state) {
    drupal_set_message(t('Hi %name, your phone number is %phone.', array(
      '%name' => $form_state['values']['name'],
      '%phone' => $form_state['values']['phone'],
    )));
  }


The function drupal_get_form() from Drupal 7 has been removed. In Drupal 8, we have two ways to load and render a form.


  // Drupal 8 - Method 1:
  $form = \Drupal::formBuilder()->getForm('\Drupal\example\Form\ExampleForm');
  return $form;

  // Drupal 8 - Method 2 Edit some fields before it is rendered:
  $form_state = new FormState();
  $form = \Drupal::formBuilder()->buildForm('\Drupal\example\Form\ExampleForm', $form_state);

  // Change title of the form.
  $form['phone']['#title'] = 'Custom Phone Title';

  return $form;  


  // Drupal 7 equivalent:
  $form = drupal_get_form('example_form');
  $form['phone']['#title'] = 'Custom Phone Title';
  return render($form);


Please check the next tutorial where I will show you how to alter a form and how to attach a custom validation/submit to an exiting form.

Sign in your account to have access to different features

Forgot your details?

TOP