Specbee: Revitalize Your Forms: Enhancing User Experience with Drupal's Form API

Revitalize Your Forms: Enhancing User Experience with Drupal's Form API Nitin Lama 11 Apr, 2023 Subscribe to our Newsletter Now Subscribe Leave this field blank

Did you know “form fatigue” is a thing?! It’s a feeling of exhaustion when you have to fill out too many forms. But forms are an integral part of a website and no site owner can (or should) do without them. So how can you make sure your website helps reduce form fatigue? Easy! Keep it simple and short, offer clear and concise instructions, break up long forms, and use autofill. Most important of all, make sure you’re offering a breezy user experience to fill them out.

Drupal’s Form API offers a way to create easily customizable and themeable forms to blend well with any website. It provides developers with a set of functions and APIs to create, validate and process forms in Drupal. Take a deeper dive into the amazing Drupal Form API and find out how you can implement it in your next project.

Image removed.

Why Form API

As you know, forms are a crucial part of every website because they allow users to interact with them by submitting data. Using Drupal's Form API, developers can create unique forms for various purposes, including contact, login, and registration. A few reasons why you should consider Form API:

  1. It is easy to use and does not require much coding experience. You can create forms using a set of simple and intuitive functions.
  2. It provides built-in validation functions that allow you to validate form data easily. 
  3. Comes with built-in security features that help prevent attacks like cross-site scripting (XSS) and cross-site request forgery (CSRF).
  4. It is highly customizable and can be used to create complex forms with multiple fields, buttons, and actions.
  5. Form APIs are themeable, so developers can change CSS and HTML to make their forms look however they want.
  6. It can be easily integrated with other Drupal APIs.

Things you need to know before building forms

There are various kinds of forms that are often used in Drupal. Each contains a base class that you can extend in a unique module of your own design.

First, identify the type of form you need to build:

  • A generic form. Extend FormBase.
  • A configuration form that enables administrators to update a module's settings. Extend ConfigFormBase.

Any form that has FormBase in its hierarchy must implement the following methods since FormBase implements FormInterface.

To create a generic custom form with the Form API, you'll need to define a function that returns an array of form elements inside buildForm(). The key of each element is the name of the form element, and the value is an array of properties that define the element. For example, to create a text field, you would define an element like this:

$form['emp_name'] = [ '#type' => 'textfield', '#title' => $this->t('Enter Name'), '#required' => TRUE, ];

Adding validation

Form API also provides a way to validate user input. You can add validation functions to your form definition that will be called when the form is submitted. If a validation function returns an error message, the form submission will be prevented and the error message will be displayed to the user.

To add a validation function, you will need to implement a validateForm().

Processing form submissions

When a form is submitted, Drupal calls a submission function that you define. The submission function can perform any necessary processing of the form data, such as saving it to the database

To define a submission function, you will need to implement a submitForm()

Integrate the form in a request

To integrate this form into a Drupal site's URI structure, use a route like the following:

example.form: path: '/example-form' defaults: _title: 'Example form' _form: '\Drupal\example\Form\ExampleForm' requirements: _permission: 'access content'

The _form key tells the routing system that the provided class name is a form class to be instantiated and handled as a form.

Creating a custom form with Drupal Form API

Follow these easy step to begin the process of creating a custom form with Drupal’s Form API:

  1. Create a .info.yml inside a custom module. (As we are creating a separate module for custom forms, this step is not required for adding forms in an existing module).
  2. Create a form class for returning the form array. (custom_module/src/Form/Registration.php
  3. Create a .routing.yml file
  4. Create a .module and hook_form_alter() and/or hook_form_FORM_ID_alter() to alter the form (If needed).

Here is a complete example of an employee registration form:

Folder structure:

Image removed.

 

1. employee_registration.info.yml

name: Employee Registration Form type: module description: Custom module for implementing custom employee registration form. core_version_requirement: ^9 || ^10 package: Custom

2. src/Form/Registration.php

<?php namespace Drupal\employee_registration\Form; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; /** * Implements a custom form. */ class Registration extends FormBase { /** * {@inheritdoc} */ public function getFormId() { return 'employee_registration_form'; } /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $form['emp_name'] = [ '#type' => 'textfield', '#title' => $this->t('Enter Name'), '#required' => TRUE, ]; $form['emp_no'] = [ '#type' => 'textfield', '#title' => $this->t('Enter Employee Number'), '#required' => TRUE, ]; $form['emp_mail'] = [ '#type' => 'email', '#title' => $this->t('Enter Email ID'), '#required' => TRUE, ]; $form['emp_phone'] = [ '#type' => 'tel', '#title' => $this->t('Enter Contact Number'), ]; $form['emp_dob'] = [ '#type' => 'date', '#title' => $this->t('Enter DOB'), '#required' => TRUE, ]; $form['emp_gender'] = [ '#type' => 'select', '#title' => $this->t('Select Gender'), '#options' => [ 'Male' => $this->t('Male'), 'Female' => $this->t('Female'), 'Other' => $this->t('Other'), ], ]; $form['submit'] = [ '#type' => 'submit', '#value' => $this->t('Save'), '#button_type' => 'primary', ]; return $form; } /** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { if (strlen($form_state->getValue('emp_phone')) < 10) { $form_state->setErrorByName('emp_phone', $this->t('The phone number is too short. Please enter a full phone number.')); } } /** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { // Processing form data. $this->messenger()->addMessage($this->t("Employee Registration Done!!")); foreach ($form_state->getValues() as $key => $value) { $this->messenger()->addMessage($key . ': ' . $value); } } }

3. employee_registration.routing.yml

employee_registration.form: path: '/registration-form' defaults: _title: 'Employee Registration' _form: '\Drupal\employee_registration\Form\Registration' requirements: _permission: 'access content'

Result:

Image removed.

 

Image removed.

Final Thoughts

Form API lets you create complex and customized forms with validation and processing functions in Drupal. When you use Form API, you can be sure that your forms are consistent and easy to use for your users. Looking for a Drupal agency to help you build a user-friendly experience for your audience? Talk to our Drupal experts today!

Author: Nitin Lama

Meet Nitin Lama, a backend Drupal Developer at Specbee who believes progressing one day at a time could go a long way. Swimming is his hobby, but he’s a huge music lover and enjoys producing and exploring new music. Music and cooking act as therapy for him. Space and tech are his best conversation starters when meeting new people. If dreams came true, he’d be traveling to a Voyager station!

Email Address Subscribe Leave this field blank Drupal Drupal Module Drupal Development Drupal Planet

Leave us a Comment

 

Recent Blogs

Image Image removed.

Revitalize Your Forms: Enhancing User Experience with Drupal's Form API

Image Image removed.

Cheat Codes in Music - Nitin Lama’s Life in a Mirage

Image Image removed.

Customizing Content Display in Drupal: A Guide to Display Modes

Want to extract the maximum out of Drupal? TALK TO US

Featured Case Studies

Image removed.Image removed.

Upgrading the web presence of IEEE Information Theory Society, the most trusted voice for advanced technology

Explore
Image removed.Image removed.

A Drupal powered multi-site, multi-lingual platform to enable a unified user experience at SEMI

Explore
Image removed.Image removed.

Great Southern Homes, one of the fastest growing home builders in the US, sees greater results with Drupal

Explore
View all Case Studies

Talking Drupal: Talking Drupal #394 - Open Source in K-12 Education

Today we are talking about Open Source in K-12 Education with Stu Keroff.

For show notes visit: www.talkingDrupal.com/394

Topics
  • What is the Penguin Corp
  • Why is Open Source important
  • How can educators bring open soiurce to their classroom
  • How difficult is it to change from closed to open source
  • What are some resources
  • Youtube Channel
  • Hurdles to introducing open source
  • Types of software you’ve introduced
  • Sourcing hardware
  • What to say to the question: Why is this important?
  • Video games
  • Statistics
  • Homeschooling
  • How to help
Resources Guests

Stu Keroff - @studoeslinux

Hosts

Nic Laflin - www.nLighteneddevelopment.com @nicxvan John Picozzi - www.epam.com @johnpicozzi Kat Shaw - drupal.org/u/katannshaw @katannshaw

MOTW Correspondent

Martin Anderson-Clutz - @mandclu H5P Provides a toolset for adding HTML5 rich content to your site: interactive videos, presentations, quizzes, games, and more.

The Drop Times: The Pleasure of Reporting Drupal

Journalism, in essence, is the job of painting a picture in the readers’ minds. Unlike actual painting, we don’t use colours. Instead, languages, words and letters fill our palette. We use it to report the facts that lie before us to a broader audience. The process of creating a news story is indeed complex. It requires us to go through layers of verification, self-doubt and delivering near-perfect write-ups within the deadline. If the work fails to entice pleasure or provide enjoyment, it becomes a meaningless burden.

At TheDropTimes (TDT), our journalistic work revolves around Drupal. Day in and day out, we fix our eyes on Drupal-related developments around the globe. We know there is a thriving community waiting for more news about Drupal. That’s the first stimulus of pleasure in reporting—Drupal is not just software. Drupal is a microcosm of human endeavour. The Free and Open-Source platform stands in the middle, surrounded by an ecosystem relentlessly working to improve it. The freedom that Drupal hands down to its users is yet another pleasure trigger. Who in the world dislikes space? Liberty opens the skies and lets magic rain. The same is happening with Drupal. In short, though reflecting upon the jargon-rich Drupal is a challenge for the soft-hearted, it gives us meaningful pleasure—the pleasure of reporting Drupal.

Check out the hand-picked stories from the past week:

To start with, TDT has launched a new series of blogs on its behind-the-scene tales. The first of the series, written by Vimal Joseph, throws light on the technology that powers TDT. Read how Drupal and Thunder distribution light up TheDropTimes.

Dries Buytaert, Drupal’s founder, has published a new blog post about the evolution of Drupal’s composability. This article introduces the readers to Dries’ blog and points out how Drupal will provide an ‘App-Store’ like experience. Dries’ earlier blog post was a myth-buster questioning the assertion that Static Site generators are faster than Content Management Systems.

To know about the automation of an e-commerce order on Drupal, read our take on the blog published by ComputerMinds. This article will be helpful for anyone interested in ‘Microsites’ developed by LocalGov Drupal and its ability to handle multiple sites. Also, see why Danny Bluestone thinks Drupal is the best enterprise choice.

The Drop Times is now a media partner for upcoming events like the Stanford WebCamp, Drupal Developer Days, Vienna and DrupalCamp Ruhr.

Drupal4Gov is hosting an in-person half-day event on the 18th. DrupalJam has opened the call for speakers. Drupal Diversity and Inclusion Camp dates are declared. The Melbourne Drupal Group is organizing another meetup on 13 April 2023. Florida DrupalCamp organizers have announced the dates for the 2024 edition of the camp.

Please read the article about Drupal Associations’ call to find community at DrupalCon Pittsburgh. Drupal Swag Shop is pursuing promoting sustainability through its products.

SpecBee’s new blog post offers readers a comprehensive guide to understanding display modes and their applications in Drupal. To clear any doubts regarding adding a JavaScript Library to an Emulsify component, refer to this tutorial. Any Drupal developer who wants to take their skills to the next level must not miss this online training scheduled on the 11th. A11yTalks has announced its upcoming meetup on 12 April 2023 at 6:00 PM EDT. The topic of the meetup is ‘Shifting Left: How CMS Accessibility Can Help.’

Global digital transformation services and product engineering company, EPAM, has been named a Top IT Sourcing Vendor in the Nordics by the independent research organization Whitelane Research. The Australian Web Industry Association has declared the finalists for the Australian Web Awards 2023. Morpht and other Drupal-based service providers have secured a place in the final list. Read the article to know more about the awards and the finalists.

A group of developers seeks responses from the Drupal community regarding the Field UI. Don’t forget to fill it out and help them improve Field UI’s performance.

Sincerely,
Thomas Alias K.
Sub-Editor

LN Webworks: Opigno:An Innovative Drupal based Learning Management System

A Learning Management System or LMS is a concept of eLearning that uses web-based technologies for delivering educational materials, courses, and training programs. LMS helps instructors create and deliver content on a platform that the students can access and learn from. This technology is generally used by businesses, educational institutions, government agencies, etc., for collecting, organizing, sharing knowledge, and training people. What is Opigno LMS Several learning management systems on the market facilitate eLearning, but when it comes to a customizable e-Learning platform, nothing can beat Opigno. It is a Drupal-based LMS that helps organizations effectively train and educate employees and members. This open-source LMS is powered by Drupal, a robust content management system with 124k active contributors and 1.39 million members around the world. Opigno LMS started its journey of offering a modern learning management system in 2013. Since then, it has succeeded in providing an exceptional learning experience by utilizing the flexibility and scalability of a Drupal CMS.

LN Webworks: Improve the Performance of Drupal Websites using Core Web Vitals

A highly optimized website can improve search engine ranking and user experience. As a result, such websites receive millions of visitors each day and provide a better customer experience, thereby boosting revenue. The goal of ranking higher on search engines is to attract the most traffic and relevant visitors to your website. In addition to providing a great user experience, optimizing a website's performance can also prevent visitors from switching to your competitors. According to studies, users are losing patience, and their attention spans are also decreasing. About 47% of users expect every website to load within a few seconds. As Google wants to make searching faster, easier, and more useful for users, it will favor websites that load quickly. When your site grows in popularity, optimizing the loading time becomes even more crucial, and shaving off a few milliseconds now can have a big impact later on.