
What is FormBase in Drupal?
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:
Class | Use Case |
---|---|
FormBase | Generic forms (like contact forms or other user-submitted forms) |
ConfigFormBase | Forms for editing configuration settings |
ConfirmFormBase | Forms 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