Reader small image

You're reading from  Drupal 10 Development Cookbook - Third Edition

Product typeBook
Published inFeb 2023
PublisherPackt
ISBN-139781803234960
Edition3rd Edition
Tools
Concepts
Right arrow
Authors (2):
Matt Glaman
Matt Glaman
author image
Matt Glaman

Matt Glaman is an open source developer who has been working with Drupal since 2013. Since then, he has contributed to Drupal core and over 60 community projects. He is also a speaker at multiple Drupal community events, including DrupalCon. Matt is currently a principal software engineer at Acquia and was previously a product lead at Centarro, helping maintain Drupal Commerce.
Read more about Matt Glaman

Kevin Quillen
Kevin Quillen
author image
Kevin Quillen

Kevin Quillen has been working with Drupal since 2006. He's contributed several community modules, and built websites using Drupal for brands such as Dogfish Head Craft Brewery, the National Bureau of Economics, Harvard University, MTV, Yale University, Verizon, the Museum of Science, and countless others. You can find him engaged and helping community members on Slack, Drupal StackExchange, or sharing his thoughts on his personal blog. Kevin is also an Acquia Triple Certified Drupal Expert, an Acquia Certified Site Studio Site Builder, and an Acquia Certified Cloud Platform Pro. He is currently a principal developer and Drupal practice lead at Velir.
Read more about Kevin Quillen

View More author details
Right arrow

Creating Forms with the Form API

This chapter will cover the usage of the Form API, which is used to create forms in Drupal without writing any HTML! This chapter will walk you through creating a form to manage a custom piece of configuration with validation. You will also learn how to implement conditional form fields using the states property to control whether an element is hidden, visible, required, or more. We will also demonstrate how AJAX can be implemented in Drupal forms to provide dynamic form elements. Finally, you will learn how to alter other forms in Drupal to customize their application.

In this chapter, we will go through the following recipes:

  • Creating a custom form and saving configuration changes
  • Validating form data
  • Specifying conditional form elements
  • Using AJAX in a Drupal form
  • Customizing existing forms in Drupal

Technical requirements

This chapter will require an installed custom module. In the following recipes, the module name is mymodule. Replace as appropriate. You can find the full code used in this chapter on GitHub: https://github.com/PacktPublishing/Drupal-10-Development-Cookbook/tree/main/chp07

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…

  1. 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 the Form namespace:
    mkdir -p src/Form
  2. Create a file named CompanyForm.php in the Form directory. This will hold our CompanyForm form class.
  3. Our CompanyForm class will extend the FormBase 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...

Validating form data

We will expand on the form created in the last recipe to add validation. We will add validation information to form elements in the company form. There is also a validateForm method that can be used to programmatically identify errors and prevent form submission.

Getting ready

This recipe will use the form class created in the Creating a custom form and saving configuration changes recipe.

How to do it…

  1. First, we will make the form elements required. This will prevent submitting the form without providing values. Update the form elements in buildForm to match the following:
        $form['company_name'] = [
          '#type' => 'textfield',
          '#title' => 'Company name',
          '#required' => TRUE,
          '#default_value' => $company_settings...

Specifying conditional form elements

The Form API provides a mechanism for defining form element states. These states are mapped to JavaScript interactions that can control whether an element is required, visible, and more. In this example, we will demonstrate a form that has a disabled submit button until a checkbox is checked.

How to do it…

  1. Create a file named ApprovalRequiredForm.php in the src/Form directory for your module to hold the ApprovalRequiredForm form class.
  2. We will define the ApprovalRequiredForm class with a form ID of mymodule_approval_form:
    <?php
    namespace Drupal\mymodule\Form;
    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;
    class ApprovalRequiredForm extends FormBase {
      public function getFormId() {
        return 'mymodule_approval_form';
      }
      public function buildForm(array $form,
        FormStateInterface $form_state) {
        return...

Using AJAX in a Drupal form

The Form API has a mechanism to perform AJAX requests without writing any JavaScript. In this example, we will create a counter with an increment and decrement button.

How to do it…

  1. Create a file named CounterForm.php in the src/Form directory for your module to hold the CounterForm form class.
  2. We will define the CounterForm class with a form ID of mymodule_counter_form:
    <?php
    namespace Drupal\mymodule\Form;
    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;
    class CounterForm extends FormBase {
      public function getFormId() {
        return 'mymodule_counter_form';
      }
      public function buildForm(array $form,
        FormStateInterface $form_state) {
        return $form;
      }
      public function submitForm(array &$form,
        FormStateInterface $form_state) {
      }
    }
  3. In the buildForm method...

Customizing existing forms in Drupal

The Form API does not just provide a way to create forms. There are ways to alter existing forms through hooks in a custom module. By using this technique, new elements can be added, default values can be changed, and elements can even be hidden from view to simplify the user experience.

The altering of a form does not happen in a custom class; this is a hook defined in the module file. In this recipe, we will use the hook_form_FORM_ID_alter() hook to add a telephone field to the site’s configuration form.

How to do it…

  1. Ensure that your module has a .module file to contain hooks, such as mymodule.module.
  2. We will implement hook_form_FORM_ID_alter for the system_site_information_settings form:
    <?php
    use Drupal\Core\Form\FormStateInterface;
    function mymodule_form_system_site_information
      _settings_alter(array &$form, FormStateInterface
        $form_state) {
      // Code to alter form...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Drupal 10 Development Cookbook - Third Edition
Published in: Feb 2023Publisher: PacktISBN-13: 9781803234960
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Matt Glaman

Matt Glaman is an open source developer who has been working with Drupal since 2013. Since then, he has contributed to Drupal core and over 60 community projects. He is also a speaker at multiple Drupal community events, including DrupalCon. Matt is currently a principal software engineer at Acquia and was previously a product lead at Centarro, helping maintain Drupal Commerce.
Read more about Matt Glaman

author image
Kevin Quillen

Kevin Quillen has been working with Drupal since 2006. He's contributed several community modules, and built websites using Drupal for brands such as Dogfish Head Craft Brewery, the National Bureau of Economics, Harvard University, MTV, Yale University, Verizon, the Museum of Science, and countless others. You can find him engaged and helping community members on Slack, Drupal StackExchange, or sharing his thoughts on his personal blog. Kevin is also an Acquia Triple Certified Drupal Expert, an Acquia Certified Site Studio Site Builder, and an Acquia Certified Cloud Platform Pro. He is currently a principal developer and Drupal practice lead at Velir.
Read more about Kevin Quillen