formbase

What is FormBase in Drupal?

  • Profile picture of Mcs
  • by Mcs July 1, 2025

In Drupal, FormBase is an abstract base class provided by the Drupal Form API. It serves as a starting point for building custom forms.

It provides shared logic and structure that you can extend when creating your own forms, such as contact forms, config forms, or other interactive features.

Where is FormBase Used?

Drupal has different base classes for different types of forms:

ClassUse Case
FormBaseGeneric forms (like contact forms or other user-submitted forms)
ConfigFormBaseForms for editing configuration settings
ConfirmFormBaseForms that ask for user confirmation (e.g., delete confirmation)

How Does It Work?

When you create a form using FormBase, you write some special functions to define:

  • What your form looks like (fields, buttons)
  • What happens when the form is submitted

Key Methods in FormBase

Here are the essential methods you'll need to override when using FormBase:

1. getFormId()

This method returns a unique string identifying your form.

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

2. buildForm()

This is where you add form fields (like textboxes, email fields, buttons).

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

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

 return $form;
}

3. submitForm()

This runs when someone submits the form.

public function submitForm(array &$form, FormStateInterface $form_state) {
 $name = $form_state->getValue('name');
 \Drupal::messenger()->addMessage('Hello, ' . $name);
}

Where Do You Put This Code?

In your custom module: modules/custom/my_module/src/Form/MyForm.php

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <br> <p> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <cite> <dl> <dt> <dd> <a hreflang href> <blockquote cite> <ul type> <ol type start> <strong> <em> <code> <li>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.