SlideShare a Scribd company logo
1 of 16
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 7Zsolt Tasnadi
 
Drupal csu-open atriumname
Drupal csu-open atriumnameDrupal csu-open atriumname
Drupal csu-open atriumnameEmanuele 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 DrupalFredric Mitchell
 
Entity Query API
Entity Query APIEntity Query API
Entity Query APImarcingy
 
Drupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of UsageDrupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of UsageRonald Ashri
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Formsdrubb
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comJD Leonard
 
14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilor14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilorRazvan Raducanu, PhD
 
Writing Sensible Code
Writing Sensible CodeWriting Sensible Code
Writing Sensible CodeAnis 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 Moduledrubb
 
Writing Drupal 5 Module
Writing Drupal 5 ModuleWriting Drupal 5 Module
Writing Drupal 5 ModuleSammy 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 jsonabksharma
 
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 CairoMohamed Mosaad
 
UITableView Pain Points
UITableView Pain PointsUITableView Pain Points
UITableView Pain PointsKen 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 2James 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 Ajax Form Training

laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usagePavel 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 technologyDaniel Knell
 
WordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta BoxesWordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta BoxesJeremy Green
 
Symfony CoP: Form component
Symfony CoP: Form componentSymfony CoP: Form component
Symfony CoP: Form componentSamuel 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 2011camp_drupal_ua
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant TrainingAidIQ
 
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 fieldIvan Zugec
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony AppsKris 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 AJAXDrupalSib
 
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 languageLovely Professional University
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus 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, 2018Balázs Tatár
 
Full Stack Web Development.pptx
Full Stack Web Development.pptxFull Stack Web Development.pptx
Full Stack Web Development.pptxDineshGokuladas
 

Similar to Drupal 9 Ajax Form Training (20)

D8 Form api
D8 Form apiD8 Form api
D8 Form api
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
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

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 

Recently uploaded (20)

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Drupal 9 Ajax Form Training

  • 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; } }