How to add a Custom Form to your Drupal 8 module

In order to add a Form to your Drupal 8 module, you first need to add a route in the yourmodulename.routing.yml file, you can do that as follows

commerce_amazon_slider.configure_slider_settings:
  path: '/admin/commerce/config/commerce-amazon-slider/configure-slider-settings'
  defaults:
    _form:  '\Drupal\commerce_amazon_slider\Controller\ConfigureSliderSettingsForm'
    _title: 'Configure Amazon Slider Settings'
  requirements:
    _permission: 'administer commerce_amazon_slider'

Then we need to create the Form class under the same path we wrote in the .routing.yml file, under your_module_folder/src/Controller/FormClassName.php, The file name and class name should match the entries added in your .routing.yml file, like the following example

<?php

namespace Drupal\commerce_amazon_slider\Controller;

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

class ConfigureSliderSettingsForm extends FormBase
{
    public function getFormId()
    {
        return 'commerce_amazon_slider_slider_settings_form';
    }

    public function buildForm(array $form, FormStateInterface $form_state)
    {
        

        return $form;
    }

    public function submitForm(array &$form, FormStateInterface $form_state)
    {
      
    }
}

You then need to add the form fields and add code to the submitForm function to save the form fields, like the following example

public function buildForm(array $form, FormStateInterface $form_state)
{
   $form['show_on_pages'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Show the Slider on the following pages'),
      '#description' => $this->t('Enter the path of the pages you want the slider to render on, each path on a separate line'),
      '#default_value' => $this->config('commerce_amazon_slider.settings')->get('show_on_pages'),
   ];

   $form['actions'] = [
      '#type' => 'actions',
   ];

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

   return $form;
}

public function submitForm(array &$form, FormStateInterface $form_state)
{
   $show_on_pages = $form_state->getValue('show_on_pages');
   \Drupal::configFactory()->getEditable('commerce_amazon_slider.settings')->set('show_on_pages', $show_on_pages)->save();
}

Then when you navigate to the form using the path defined in your route you should see the page, and when you save the values should be retained in the fields

Thank you and looking forward to help you do more with Drupal

Share this post