Creating a custom form and saving configuration changes
In this recipe, we will create a form that allows saving the company name and phone number for the website to the configuration. Forms are defined as classes that implement \Drupal\Core\Form\FormInterface
. \Drupal\Core\Form\FormBase
serves as a standard base class for forms. We will extend this class to create a new form that saves the custom configuration.
How to do it…
- First, we need to create the
src/Form
directory in the module’s directory. We will put our form class in this directory, which gives our form class theForm
namespace:mkdir -p src/Form
- Create a file named
CompanyForm.php
in theForm
directory. This will hold ourCompanyForm
form class. - Our
CompanyForm
class will extend theFormBase
class provided by Drupal core:<?php
namespace Drupal\mymodule\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class CompanyForm extends FormBase {
public function...