SlideShare a Scribd company logo
Drupal 9 Training
Topics
1. Create a custom form with Country and City Fields as select list and show data of cities when particular
country is selected using ajax change event.
Ajax Module Example
Step 1: Create .info.yml
Let's create a yml file. A yml file is a file that specifies the configuration for a file i.e., to store metadata information
about the project
name: Ajax Example
description: User Name or Email Ajax Validation
core: 8.x
type: module
Step 2: Creating .routing.yml Let’s create a .routing.yml called ajax_example.routing.yml. Each route is defined as a
machine name in the form of module_name.route_name
path: '/ajax_example'
defaults:
_form: 'Drupalajax_exampleFormAjaxExampleForm'
_title: 'Ajax Example'
requirements:
_permission: 'access content'
Step 3: Create AjaxExampleForm.php
Create a new file called AjaxExampleForm.php inside of src/Form/{AjaxExampleForm.php}.
getFormId() function is used to create a unique id to the form.
buildForm() function is used to create the form and it has a textfield to validate the username using #ajax. Drupal
provides the property ‘#ajax’ to a form element in your form array, to trigger an Ajax response.
<?php
/**
* @file
* Contains Drupalajax_exampleAjaxExampleForm
*/
namespace Drupalajax_exampleForm;
use DrupalCoreFormFormBase;
use DrupalCoreFormFormStateInterface;
use DrupalComponentUtilityUrlHelper;
use DrupalCoreAjaxAjaxResponse;
use DrupalCoreAjaxChangedCommand;
use DrupalCoreAjaxCssCommand;
use DrupalCoreAjaxHtmlCommand;
use DrupalCoreAjaxInvokeCommand;
use DrupalCoreAjaxCommandInterface;
class AjaxExampleForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'resume_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$row[] = static::get_data();
$header = array('ID', 'Country', 'City');
if (!empty($row)) {
$form['table'] = [
'#type' => 'table',
'#header' => $header,
'#rows' => $row,
];
}
$country = array('none_country' => 'None', 'india' => 'India', 'pakistan' => 'Pakistan',
'srilanka' => 'Srilanka', 'bangladesh' => 'Bangladesh');
$default_state = array('Maharashtra', 'Gujrat');
$form['country'] = array(
'#type' => 'select',
'#title' => ('Country'),
'#options' => $country,
'#ajax' => array(
'callback' => '::dependent_state',
//'effect' => 'fade',
'event' => 'change',
'wrapper' => 'state',
),
);
$country = $form_state->getValues();
$selected_country = !empty($country['country']) ? $country['country'] : 'none_country';
//dsm($selected_country);
if ($selected_country == 'none_country') {
$options = array('none_state' => 'None');
}
else if ($selected_country == 'india') {
$options = array('maharashtra' => 'Maharashtra', 'gujrat' => 'Gujrat');
}
else if ($selected_country == 'pakistan') {
$options = array('lahore' => 'Lahore', 'karachi' => 'Karachi');
}
else if ($selected_country == 'srilanka') {
$options = array('colombo' => 'Colombo', 'kandy' => 'Kandy');
}
else if ($selected_country == 'bangladesh') {
$options = array('dhaka' => 'Dhaka', 'chittagong' => 'Chittagong');
}
$form['state'] = array(
'#type' => 'select',
'#title' => ('State'),
'#options' => $options,
'#prefix' => '<div id="state">',
'#suffix' => '</div>',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Display result.
$data = $form_state->getValues();
$country = $data['country'];
$state = $data['state'];
db_merge('location')
->insertFields(array(
'country' => ucfirst($country),
'state' => ucfirst($state),
))
->updateFields(array(
'country' => ucfirst($country),
'state' => ucfirst($state),
))
->key(array('id' => 1))
->execute();
}
public function dependent_state($form, $form_state) {
return $form['state'];
}
public function get_data() {
$db = Drupal::database();
$data = $db->select('location', 'l')
->fields('l')
->execute()
->fetchAssoc();
return $data;
}
}

More Related Content

What's hot

Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7
Zsolt Tasnadi
 
Drupal csu-open atriumname
Drupal csu-open atriumnameDrupal csu-open atriumname
Drupal csu-open atriumname
Emanuele Quinto
 
Top Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalTop Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in Drupal
Fredric Mitchell
 
Entity Query API
Entity Query APIEntity Query API
Entity Query API
marcingy
 
Drupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of UsageDrupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of Usage
Ronald Ashri
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Forms
drubb
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
JD Leonard
 
14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilor14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilor
Razvan Raducanu, PhD
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
Pradeep Saraswathi
 
Karan - form search
Karan - form searchKaran - form search
Karan - form search
karanchanana1
 
Writing Sensible Code
Writing Sensible CodeWriting Sensible Code
Writing Sensible Code
Anis Ahmad
 
Revisiting SOLID Principles
Revisiting  SOLID Principles Revisiting  SOLID Principles
Revisiting SOLID Principles
Anis Ahmad
 
Drupal 8 Sample Module
Drupal 8 Sample ModuleDrupal 8 Sample Module
Drupal 8 Sample Module
drubb
 
Migrare da symfony 1 a Symfony2
 Migrare da symfony 1 a Symfony2  Migrare da symfony 1 a Symfony2
Migrare da symfony 1 a Symfony2
Massimiliano Arione
 
WordCamp London 2013
WordCamp London 2013WordCamp London 2013
WordCamp London 2013
Ivelina Dimova
 
Writing Drupal 5 Module
Writing Drupal 5 ModuleWriting Drupal 5 Module
Writing Drupal 5 Module
Sammy Fung
 
Javascript session june 2013 (iii) jquery json
Javascript session june 2013 (iii) jquery   jsonJavascript session june 2013 (iii) jquery   json
Javascript session june 2013 (iii) jquery json
abksharma
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
Mohamed Mosaad
 
UITableView Pain Points
UITableView Pain PointsUITableView Pain Points
UITableView Pain Points
Ken Auer
 
The City Bars App with Sencha Touch 2
The City Bars App with Sencha Touch 2The City Bars App with Sencha Touch 2
The City Bars App with Sencha Touch 2
James Pearce
 

What's hot (20)

Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7
 
Drupal csu-open atriumname
Drupal csu-open atriumnameDrupal csu-open atriumname
Drupal csu-open atriumname
 
Top Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalTop Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in Drupal
 
Entity Query API
Entity Query APIEntity Query API
Entity Query API
 
Drupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of UsageDrupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of Usage
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Forms
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
 
14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilor14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilor
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
Karan - form search
Karan - form searchKaran - form search
Karan - form search
 
Writing Sensible Code
Writing Sensible CodeWriting Sensible Code
Writing Sensible Code
 
Revisiting SOLID Principles
Revisiting  SOLID Principles Revisiting  SOLID Principles
Revisiting SOLID Principles
 
Drupal 8 Sample Module
Drupal 8 Sample ModuleDrupal 8 Sample Module
Drupal 8 Sample Module
 
Migrare da symfony 1 a Symfony2
 Migrare da symfony 1 a Symfony2  Migrare da symfony 1 a Symfony2
Migrare da symfony 1 a Symfony2
 
WordCamp London 2013
WordCamp London 2013WordCamp London 2013
WordCamp London 2013
 
Writing Drupal 5 Module
Writing Drupal 5 ModuleWriting Drupal 5 Module
Writing Drupal 5 Module
 
Javascript session june 2013 (iii) jquery json
Javascript session june 2013 (iii) jquery   jsonJavascript session june 2013 (iii) jquery   json
Javascript session june 2013 (iii) jquery json
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
 
UITableView Pain Points
UITableView Pain PointsUITableView Pain Points
UITableView Pain Points
 
The City Bars App with Sencha Touch 2
The City Bars App with Sencha Touch 2The City Bars App with Sencha Touch 2
The City Bars App with Sencha Touch 2
 

Similar to Drupal 9 training ajax

D8 Form api
D8 Form apiD8 Form api
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
Azim Kurt
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
Barang CK
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
Pavel Makhrinsky
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
Fabien Potencier
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
Daniel Knell
 
WordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta BoxesWordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta Boxes
Jeremy Green
 
Symfony CoP: Form component
Symfony CoP: Form componentSymfony CoP: Form component
Symfony CoP: Form component
Samuel ROZE
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
camp_drupal_ua
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant Training
AidIQ
 
Fields in Core: How to create a custom field
Fields in Core: How to create a custom fieldFields in Core: How to create a custom field
Fields in Core: How to create a custom field
Ivan Zugec
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
Kris Wallsmith
 
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
Михаил Крайнюк - Form API + Drupal 8: Form and AJAXМихаил Крайнюк - Form API + Drupal 8: Form and AJAX
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
DrupalSib
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
Viswanath Polaki
 
The HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageThe HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup language
Lovely Professional University
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
Marcus Ramberg
 
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Balázs Tatár
 
Symfony tips and tricks
Symfony tips and tricksSymfony tips and tricks
Symfony tips and tricks
Mariusz Kozłowski
 
Full Stack Web Development.pptx
Full Stack Web Development.pptxFull Stack Web Development.pptx
Full Stack Web Development.pptx
DineshGokuladas
 

Similar to Drupal 9 training ajax (20)

D8 Form api
D8 Form apiD8 Form api
D8 Form api
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
WordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta BoxesWordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta Boxes
 
Symfony CoP: Form component
Symfony CoP: Form componentSymfony CoP: Form component
Symfony CoP: Form component
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant Training
 
Fields in Core: How to create a custom field
Fields in Core: How to create a custom fieldFields in Core: How to create a custom field
Fields in Core: How to create a custom field
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
Михаил Крайнюк - Form API + Drupal 8: Form and AJAXМихаил Крайнюк - Form API + Drupal 8: Form and AJAX
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
 
The HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageThe HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup language
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
 
Symfony tips and tricks
Symfony tips and tricksSymfony tips and tricks
Symfony tips and tricks
 
Full Stack Web Development.pptx
Full Stack Web Development.pptxFull Stack Web Development.pptx
Full Stack Web Development.pptx
 

Recently uploaded

Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
Hiike
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
Dinusha Kumarasiri
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Tatiana Kojar
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 

Recently uploaded (20)

Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 

Drupal 9 training ajax

  • 2. Topics 1. Create a custom form with Country and City Fields as select list and show data of cities when particular country is selected using ajax change event.
  • 3. Ajax Module Example Step 1: Create .info.yml Let's create a yml file. A yml file is a file that specifies the configuration for a file i.e., to store metadata information about the project name: Ajax Example description: User Name or Email Ajax Validation core: 8.x type: module
  • 4. Step 2: Creating .routing.yml Let’s create a .routing.yml called ajax_example.routing.yml. Each route is defined as a machine name in the form of module_name.route_name path: '/ajax_example' defaults: _form: 'Drupalajax_exampleFormAjaxExampleForm' _title: 'Ajax Example' requirements: _permission: 'access content'
  • 5. Step 3: Create AjaxExampleForm.php Create a new file called AjaxExampleForm.php inside of src/Form/{AjaxExampleForm.php}. getFormId() function is used to create a unique id to the form. buildForm() function is used to create the form and it has a textfield to validate the username using #ajax. Drupal provides the property ‘#ajax’ to a form element in your form array, to trigger an Ajax response.
  • 6. <?php /** * @file * Contains Drupalajax_exampleAjaxExampleForm */ namespace Drupalajax_exampleForm; use DrupalCoreFormFormBase; use DrupalCoreFormFormStateInterface; use DrupalComponentUtilityUrlHelper;
  • 7. use DrupalCoreAjaxAjaxResponse; use DrupalCoreAjaxChangedCommand; use DrupalCoreAjaxCssCommand; use DrupalCoreAjaxHtmlCommand; use DrupalCoreAjaxInvokeCommand; use DrupalCoreAjaxCommandInterface; class AjaxExampleForm extends FormBase { /** * {@inheritdoc} */
  • 8. public function getFormId() { return 'resume_form'; } /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $row[] = static::get_data();
  • 9. $header = array('ID', 'Country', 'City'); if (!empty($row)) { $form['table'] = [ '#type' => 'table', '#header' => $header, '#rows' => $row, ]; } $country = array('none_country' => 'None', 'india' => 'India', 'pakistan' => 'Pakistan', 'srilanka' => 'Srilanka', 'bangladesh' => 'Bangladesh'); $default_state = array('Maharashtra', 'Gujrat'); $form['country'] = array(
  • 10. '#type' => 'select', '#title' => ('Country'), '#options' => $country, '#ajax' => array( 'callback' => '::dependent_state', //'effect' => 'fade', 'event' => 'change', 'wrapper' => 'state', ), );
  • 11. $country = $form_state->getValues(); $selected_country = !empty($country['country']) ? $country['country'] : 'none_country'; //dsm($selected_country); if ($selected_country == 'none_country') { $options = array('none_state' => 'None'); } else if ($selected_country == 'india') { $options = array('maharashtra' => 'Maharashtra', 'gujrat' => 'Gujrat'); }
  • 12. else if ($selected_country == 'pakistan') { $options = array('lahore' => 'Lahore', 'karachi' => 'Karachi'); } else if ($selected_country == 'srilanka') { $options = array('colombo' => 'Colombo', 'kandy' => 'Kandy'); } else if ($selected_country == 'bangladesh') { $options = array('dhaka' => 'Dhaka', 'chittagong' => 'Chittagong'); }
  • 13. $form['state'] = array( '#type' => 'select', '#title' => ('State'), '#options' => $options, '#prefix' => '<div id="state">', '#suffix' => '</div>', ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Submit'), );
  • 14. return $form; } /** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { // Display result. $data = $form_state->getValues(); $country = $data['country']; $state = $data['state'];
  • 15. db_merge('location') ->insertFields(array( 'country' => ucfirst($country), 'state' => ucfirst($state), )) ->updateFields(array( 'country' => ucfirst($country), 'state' => ucfirst($state), )) ->key(array('id' => 1)) ->execute();
  • 16. } public function dependent_state($form, $form_state) { return $form['state']; } public function get_data() { $db = Drupal::database(); $data = $db->select('location', 'l') ->fields('l') ->execute() ->fetchAssoc(); return $data; } }