logo

code to create custom form in Drupal 8 and 9

12
February

code to create custom form in Drupal 8 and 9
By: Anonymous | Published On: Sun, 02/12/2023 - 22:51

Here is an example of a custom form with an email and message field in Drupal 8 or 9

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

/**
 * Class CustomForm.
 */
class CustomForm extends FormBase {

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['email'] = [
      '#type' => 'email',
      '#title' => $this->t('Email'),
      '#required' => TRUE,
    ];

    $form['message'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Message'),
      '#required' => TRUE,
    ];

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

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $email = $form_state->getValue('email');
    $message = $form_state->getValue('message');

    // Perform some action with the submitted values.
    drupal_set_message($this->t('Your email is @email and message is @message', [
      '@email' => $email,
      '@message' => $message,
    ]));
  }

}

In order to display the form in a page, you need to define a route that maps to the form class. This can be done in a custom module's .routing.yml file:

custom_form.form:
  path: '/custom-form'
  defaults:
    _form: '\Drupal\custom_form\Form\CustomForm'
    _title: 'Custom Form'
  requirements:
    _permission: 'access content'

You should replace "custom_form" with the machine name of your custom module.

Need Help ?