JQuery datepicker in Drupal 9

From this article let’s understand some JavaScript terms and then see how we can attach JavaScript to the Form. We will try to see jQuery DatePicker attache to the field in form.

Below are basic concepts which are associated with JavaScript

  1. Render array – This is Multidimensional array which contain data and its metadata, which help to create a markup and display on screen. This major part to connect drupal and JavaScript with each other.
  2. IIFE - Immediately invoked function expression also known as “self-executing” function it’s a format to declare JavaScript function so they are executed as they are declared as soon as they are defined.
  3. AJAX - Asynchronous JavaScript + xml, very famous to make a background call to server without refreshing page. And it may useful to change some part or section of the page without page refresh.
  4. DOM - Document object Model, It’s a tree structure that represent the HTML code of the page which we are visiting, we can traverse through it and perform certain action as per our requirement, like change the existing behavior's of elements etc.
  5. JQuery - It’s a advance library based on JavaScript, which we can use to manipulate DOM. 

Lets take a scenario, here we have website having custom contact us module which generate a form having date field, There are two ways we can add date picker in the form

  • By using default date API of Drupal, which have some restriction for date formatting, please find eg here.
  • By using jQuery Date picker which is easy to customize. and for sake of understanding how to include JavaScript in Drupal we can use this one.

First create contact us module by creating "contactus" folder under "custom/module" and add "contactus.info.yml" file to it.

name: Contact Us
type: module
description: Custom module to generate contact us form
core_version_requirement: ^8 || ^9
package: custome        

Lets create a route file which contains url path and class location where we need to create contact us form. add "contactus.routing.yml" under 'contactus' folder.

contactus.contact_us_form
  path: /contact-us
  defaults:
    _form: '\Drupal\contactus\Form\ContactUsForm'
    _title: "Contact us"
  requirements:
    _permission: "access content":        

Then now create a contact us form for which we need to create a folder under module contactus, 'src/Form' and then create a PHP class file "ContactUsForm.php" note same file we mentioned in contactus.route.yml file.

<?php


namespace Drupal\contactus\Form;


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


/**
 * Implements the SimpleForm form controller.
 *
 * This example demonstrates a simple form with a single text input element. We
 * extend FormBase which is the simplest form base class used in Drupal.
 *
 * @see \Drupal\Core\Form\FormBase
 */
class ContactUsForm extends FormBase
{


   /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'contactus_form';
  }


  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state)
  {


    $form['title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Title'),
      '#description' => $this->t('Title must be at least 5 characters in length.'),
      '#required' => TRUE,
    ];


    // Preferred date /time to contact.
    $form['date_to_contact'] = [
      '#type' => 'textfield',
      '#title' => $this->t('date'),
    ];


    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];
    
    return $form;
  }


  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state)
  {
  }


  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state)
  {
  }
}

        

Now we need to create a JS file through which can attach date picker to the 'date_to_contact' field. Create a 'js' folder under 'contactus' module and add 'contactus.js' file to it

(function ($, Drupal) 


  jQuery('#edit-date-to-contact').datepicker();


})(jQuery, Drupal);{        

We have form with date text field, we have JS ready, now we see how we can attach this JS to form. Note - There are many ways to attach JavaScript, please check this to get more details on it. For our example we are going to attach library to the form.

For that we need to create library, creating liberay we need to add 'contactus.library.yml' file with the all information related to our JS,

contact_us_lib
  js: 
    js/contactus.js: {}
  dependencies: 
    - core/jquery.once
    - jquery_ui_datepicker/datepicker:        

Now we have created library lets attach it on our form, add below line of code on the form before submit field.

$form['#attached']['library'][] = 'contactus/contact_us_lib';        

Now coding part has been done, we need to install datepicker module using below composer command "composer require 'drupal/jquery_ui_datepicker:^1.2'" after that enable both our contactus and jquery_ui_datepicker module. Clear the cache

And then we can expect something like below,

No alt text provided for this image

Now if we want to Month, Year editable or we want to change default format from dd-mm-yyyy to something else then can do it for giving configuration to our datepicker function in JS, something like below,

(function ($, Drupal) 
  jQuery('#edit-date-to-contact').datepicker({
    dateFormat: 'dd-M-yy',// 22-May-2019
    changeMonth: true,
    changeYear: true
  });
})(jQuery, Drupal);{        

It will give us output something like below

No alt text provided for this image

Note - Please find all above code here https://github.com/pankajraundal/drupal-learnings/tree/main/modules/contactus





To view or add a comment, sign in

More articles by Pankaj Raundal

  • Drupal 10 Cache Mechanism Detailed Explanation

    In Drupal 10, caching is a critical mechanism for improving the performance and scalability of a website. Caching…

  • Drupal 10: Cache API

    Cache is a crucial component of any website, serving users faster and efficiently managing resource utilization. There…

  • Drupal 10 : Part II : How to use REST API

    In the previous article, we discussed how to expose our view to the world. Now, we want to make it secure and restrict…

  • Drupal 10 : Part I : How to use REST API

    Lets understand some key terms for REST, API - Application programming interface It's an integral part of any web…

  • GitHub Cherry-pick

    While development, some time we come across words which looks scary or we don't want to touch those. I faced same thing…

  • Definition of libraries (Include CSS and JS) for Drupal

    // Case 1: Basic library file with only JavaScript dependencies module_name.library_name: js: js/hello_world.

  • Python - Create virtual environment

    Why to create and manage separate virtual environments for your Python projects. Each environment can use different…

  • Upgrade Drupal 9 to latest version

    Check if updates are available here “admin/reports/updates” We can also check the same by using composer command ddev…

  • Drupal 9 : Multisite Setup Steps

    The site’s which share same codebase, and having its own database configuration, files and domain/URL. Where I can use…

  • Drupal 9 : Event Subscription : Utilize core dispatched events

    Events one of the important aspects of Drupal. There are many incidents where we need to add our code if some things…

Others also viewed

Explore content categories