Book Image

Drupal 8 Development Cookbook - Second Edition

By : Matt Glaman
Book Image

Drupal 8 Development Cookbook - Second Edition

By: Matt Glaman

Overview of this book

Began as a message board, Drupal today is open source software maintained and developed by a community of over 1,000,000 users and developers. Drupal is used by numerous local businesses to global corporations and diverse organizations all across the globe. With Drupal 8’s exciting features it brings, this book will be your go-to guide to experimenting with all of these features through helpful recipes. We’ll start by showing you how to customize and configure the Drupal environment as per your requirements, as well as how to install third-party libraries and then use them in the Drupal environment. Then we will move on to creating blocks and custom modules with the help of libraries. We will show you how to use the latest mobile-first feature of Drupal 8, which will help you make your apps responsive across all the major platforms. This book will also show you how to incorporate multilingual facilities in your sites, use web services and third-party plugins with your applications from inside Drupal 8, and test and deploy your apps.
Table of Contents (20 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Validating form data


All forms must implement the \Drupal\Core\Form\FormInterface. The interface defines a validation method. The validateForm method is invoked once a form has been submitted and provides a way to validate the data and halt the processing of the data if required. The form state object provides methods for marking specific fields as having the error, providing a user experience tool to alert your users to specify the problem input.

In this recipe, we will be validating the length of the submitted field.

Getting ready

This recipe will use the module and custom form created in the first Creating a form recipe.

How to do it...

  1. Open and edit the \Drupal\drupalform\Form\ExampleForm class in the src/Form directory of the module.

 

  1. Before validating the company_name value, we will need to check whether the value is empty using the isValueEmpty() method from the \Drupal\Core\Form\FormStateInterface object:
/** 
 * {@inheritdoc} 
 */ 
public function validateForm(array &$form,  FormStateInterface...