SlideShare a Scribd company logo
FormAPI + Drupal 8
Form and AJAX
Mikhail Kraynuk
Mikhail Kraynuk
Drupal Senior Developer
About my experience in Drupal
development
●  Development
●  Project management
●  Drupal audit
●  Drupal Localization
Mikhail Kraynuk
Drupal Senior Developer
Form API Drupal 8
OK
Class
namespase
function
Object-oriented programming
extends
use
Mikhail Kraynuk
Drupal Senior Developer
New Form
<?php	
  	
  
/**	
  	
  
*	
  @file	
  	
  
*	
  Contains	
  DrupalExampleFormExampleForm.	
  	
  
*/	
  	
  
	
  
namespace	
  DrupalexampleForm;	
  	
  
use	
  DrupalCoreFormFormBase;	
  	
  
use	
  DrupalCoreFormFormStateInterface;	
  	
  
	
  
/**	
  	
  
*	
  Provides	
  a	
  simple	
  example	
  form.	
  	
  
*/	
  	
  
class	
  ExampleForm	
  extends	
  FormBase	
  {	
  
	
  
	
  
}	
  
public function getFormID()
public function buildForm($form, $form_state)
public function validateForm(&$form, $form_state)
public function submitForm(&$form, &$form_state)
Mikhail Kraynuk
Drupal Senior Developer
Form ID
/**	
  	
  
	
  *	
  Implements	
  DrupalCoreFormFormInterface::getFormID().	
  	
  
	
  */	
  
public	
  function	
  getFormID()	
  {	
  	
  
	
  	
  return	
  ’my_special_form’;	
  
}	
  	
  
/**	
  	
  
	
  *	
  Form	
  builder	
  for	
  my	
  form.	
  	
  
	
  */	
  
function	
  my_special_form($form,	
  &$form_state)	
  {…} Drupal 7
Mikhail Kraynuk
Drupal Senior Developer
Form builder
/**	
  	
  
	
  *	
  Implements	
  DrupalCoreFormFormInterface::buildForm().	
  	
  
	
  */	
  
public	
  function	
  buildForm(array	
  $form,	
  FormStateInterface	
  $form_state,	
  $a	
  =	
  0)	
  {	
  	
  
	
  
	
  	
  $form['my_text_field']	
  =	
  array(	
  
	
  	
  	
  	
  '#type'	
  =>	
  'textfield',	
  
	
  	
  	
  	
  '#title'	
  =>	
  'Example',	
  
	
  	
  );	
  
	
  
	
  	
  return	
  $form;	
  	
  
}	
  	
  
Mikhail Kraynuk
Drupal Senior Developer
Form validate
/**	
  	
  
	
  *	
  Implements	
  DrupalCoreFormFormInterface::validateForm().	
  	
  
	
  */	
  
public	
  function	
  validateForm(array	
  &$form,	
  FormStateInterface	
  $form_state)	
  {	
  	
  
	
  
if (strlen($form_state-­‐>getValue('phone_number')) < 3) {
$form_state-­‐>setErrorByName('phone_number', $this-­‐>t('The phone number is too short.'));
}	
  
} 	
  	
  
Mikhail Kraynuk
Drupal Senior Developer
Form submit
/**	
  	
  
	
  *	
  Implements	
  DrupalCoreFormFormInterface::submitForm().	
  	
  
	
  */	
  
public	
  function	
  submitForm(array	
  &$form,	
  FormStateInterface	
  $form_state)	
  {	
  	
  
	
  
	
  	
  $phone	
  =	
  $form_state-­‐>getValue('phone_number');	
  
	
  
}	
  	
  	
  
Mikhail Kraynuk
Drupal Senior Developer
Get form
$form	
  =	
  Drupal::formBuilder()-­‐>getForm('DrupalExampleFormExampleForm');	
  
	
  
	
  
	
  
	
  
$form	
  =	
  Drupal::formBuilder()-­‐>getForm('DrupalExampleFormExampleForm',	
  'test');	
  
Mikhail Kraynuk
Drupal Senior Developer
Special forms
Mikhail Kraynuk
Drupal Senior Developer
Settings form
use	
  DrupalCoreFormFormBase;	
  
use	
  DrupalCoreFormConfigFormBase;	
  	
  
class	
  ExampleConfigForm	
  extends	
  ConfigFormBase	
  {	
  	
  
...	
  
	
  	
  public	
  function	
  buildForm(array	
  $form,	
  FormStateInterface	
  $form_state)	
  {	
  	
  
	
  	
  	
  	
  $form	
  =	
  parent::buildForm($form,	
  $form_state);	
  	
  
	
  	
  	
  	
  ...	
  
	
  	
  	
  	
  return	
  $form;	
  	
  
	
  	
  }	
  	
  
...	
  
}	
  
system_settings_form() Drupal 7
Mikhail Kraynuk
Drupal Senior Developer
Confirm form
use	
  DrupalCoreFormFormBase;	
  
use	
  DrupalCoreFormConfirmFormBase;	
  	
  
class	
  ExampleConfigForm	
  extends	
  ConfirmFormBase	
  {	
  	
  
...	
  
	
  	
  public	
  function	
  buildForm(array	
  $form,	
  FormStateInterface	
  $form_state)	
  {	
  	
  
	
  	
  	
  	
  $form	
  =	
  parent::buildForm($form,	
  $form_state);	
  	
  
	
  	
  	
  	
  ...	
  
	
  	
  	
  	
  return	
  $form;	
  	
  
	
  	
  }	
  	
  
...	
  
}
confirm_form() Drupal 7
Mikhail Kraynuk
Drupal Senior Developer
AJAX
Mikhail Kraynuk
Drupal Senior Developer
AJAX
OK
OK
AJAX
AJAX commands
Mikhail Kraynuk
Drupal Senior Developer
1. Add Ajax namespace
<?php	
  	
  
/**	
  	
  
*	
  @file	
  	
  
*	
  Contains	
  DrupalExampleFormExampleForm.	
  	
  
*/	
  	
  
	
  
namespace	
  DrupalexampleForm;	
  	
  
use	
  DrupalCoreFormFormBase;	
  
use	
  DrupalCoreFormFormStateInterface;	
  	
  
	
  
use	
  DrupalCoreAjaxAjaxResponse;	
  	
  
use	
  DrupalCoreAjaxHtmlCommand;	
  	
  
	
  
/**	
  	
  
*	
  Provides	
  a	
  simple	
  example	
  form.	
  	
  
*/	
  	
  
class	
  ExampleForm	
  extends	
  FormBase	
  {	
  ...	
  }	
  
Mikhail Kraynuk
Drupal Senior Developer
2. Add Ajax-callback
/**	
  	
  
*	
  Provides	
  a	
  simple	
  example	
  form.	
  	
  
*/	
  	
  
class	
  ExampleForm	
  extends	
  FormBase	
  {	
  
	
  
	
  	
  public	
  function	
  getFormID()	
  
	
  	
  public	
  function	
  buildForm(array	
  $form,	
  FormStateInterface	
  $form_state)	
  
	
  	
  public	
  function	
  validateForm(array	
  &$form,	
  FormStateInterface	
  $form_state)	
  
	
  	
  public	
  function	
  submitForm(array	
  &$form,	
  FormStateInterface	
  $form_state)	
  
	
  
	
  	
  public	
  function	
  validateAjaxPhone(array	
  &$form,	
  FormStateInterface	
  $form_state)	
  
}	
  
Mikhail Kraynuk
Drupal Senior Developer
3. Update field
public	
  function	
  buildForm(array	
  $form,	
  FormStateInterface	
  $form_state)	
  {	
  	
  
	
  	
  ...	
  
	
  	
  $form['my_phone']	
  =	
  array(	
  
	
  	
  	
  	
  '#type'	
  =>	
  'tel',	
  
	
  	
  	
  	
  '#title'	
  =>	
  $this-­‐>t('Phone number'),	
  
	
  	
  	
  	
  '#description'	
  =>	
  $this-­‐>t('Enter your phone number with “+”.'),	
  
	
  	
  	
  	
  '#ajax'	
  =>	
  array(	
  
	
  	
  	
  	
  	
  	
  'callback'	
  =>	
  array($this,	
  'validateAjaxPhone'),	
  
	
  	
  	
  	
  	
  	
  'event'	
  =>	
  'change',	
  
	
  	
  	
  	
  	
  	
  'progress'	
  =>	
  array(	
  
	
  	
  	
  	
  	
  	
  	
  	
  'type'	
  =>	
  'throbber',	
  
	
  	
  	
  	
  	
  	
  	
  	
  'message'	
  =>	
  $this-­‐>t('verifying…'),	
  
	
  	
  	
  	
  	
  	
  ),	
  
	
  	
  	
  	
  ),	
  
	
  	
  	
  	
  '#suffix'	
  =>	
  '<span	
  class=“valid-­‐message”></span>',	
  
	
  	
  );	
  
	
  	
  return	
  $form;	
  	
  
}	
  	
  
Mikhail Kraynuk
Drupal Senior Developer
4. Fill Ajax-callback
public	
  function	
  validateAjaxPhone(array	
  &$form,	
  FormStateInterface	
  $form_state)	
  {	
  	
  
	
  
	
  	
  $response	
  =	
  new	
  AjaxResponse();	
  
	
  	
  	
  
	
  	
  if (substr($form_state-­‐>getValue('my_phone'),	
  0,	
  1) == '+') {	
  
	
  	
  	
  	
  $message	
  =	
  $this-­‐>t('Phone number is correct');	
  
	
  	
  }	
  
	
  	
  else {	
  
	
  	
  	
  	
  $message	
  =	
  $this-­‐>t('Please start your phone number with “+”');	
  
	
  	
  }	
  
	
  
	
  	
  $response-­‐>addCommand(new	
  HtmlCommand('.valid-­‐message',	
  $message));	
  
	
  
	
  	
  return	
  $response;	
  	
  
}	
  	
  
Mikhail Kraynuk
Drupal Senior Developer
Ajax result
Mikhail Kraynuk
Drupal Senior Developer
Ajax result
Mikhail Kraynuk
Drupal Senior developer
Mikhail Kraynuk
Drupal Senior Developer
kraynuk.m@i20.biz
+7 961 870-26-99
Золотой спонсор:
Спасибо!
При поддержке: Серебряный спонсор:

More Related Content

What's hot

#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Decoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDDDecoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDD
Aleix Vergés
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
Michelangelo van Dam
 
First Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven DevelopmentFirst Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven Development
Nuvole
 
Magento 2 | Declarative schema
Magento 2 | Declarative schemaMagento 2 | Declarative schema
Magento 2 | Declarative schema
Kiel Pykett
 
Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)
Fabien Potencier
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
eugenio pombi
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
Leonardo Proietti
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
Hugo Hamon
 
Laravel tips-2019-04
Laravel tips-2019-04Laravel tips-2019-04
Laravel tips-2019-04
Fernando Andrés Pérez Alarcón
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
tutorialsruby
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
Leonardo Proietti
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
tutorialsruby
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Ivan Chepurnyi
 
RicoLiveGrid
RicoLiveGridRicoLiveGrid
RicoLiveGrid
tutorialsruby
 
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
Daniel Bryant
 
PHP MVC
PHP MVCPHP MVC
節子、それViewControllerやない...、FatViewControllerや...。
節子、それViewControllerやない...、FatViewControllerや...。節子、それViewControllerやない...、FatViewControllerや...。
節子、それViewControllerやない...、FatViewControllerや...。
Kenji Tanaka
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
Hugo Hamon
 

What's hot (20)

#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
 
Decoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDDDecoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDD
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
First Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven DevelopmentFirst Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven Development
 
Magento 2 | Declarative schema
Magento 2 | Declarative schemaMagento 2 | Declarative schema
Magento 2 | Declarative schema
 
Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)Beyond symfony 1.2 (Symfony Camp 2008)
Beyond symfony 1.2 (Symfony Camp 2008)
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
Laravel tips-2019-04
Laravel tips-2019-04Laravel tips-2019-04
Laravel tips-2019-04
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
 
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for PerformanceMeet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
Meet Magento Sweden - Magento 2 Layout and Code Compilation for Performance
 
RicoLiveGrid
RicoLiveGridRicoLiveGrid
RicoLiveGrid
 
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
 
PHP MVC
PHP MVCPHP MVC
PHP MVC
 
節子、それViewControllerやない...、FatViewControllerや...。
節子、それViewControllerやない...、FatViewControllerや...。節子、それViewControllerやない...、FatViewControllerや...。
節子、それViewControllerやない...、FatViewControllerや...。
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 

Similar to Михаил Крайнюк - Form API + Drupal 8: Form and AJAX

Mikhail Kraynuk. Form api. Drupal 8
Mikhail Kraynuk. Form api. Drupal 8Mikhail Kraynuk. Form api. Drupal 8
Mikhail Kraynuk. Form api. Drupal 8
DrupalSib
 
Mikhail Kraynuk. Form api. Drupal 8
Mikhail Kraynuk. Form api. Drupal 8Mikhail Kraynuk. Form api. Drupal 8
Mikhail Kraynuk. Form api. Drupal 8
i20 Group
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Forms
drubb
 
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
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
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
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
Fabien Potencier
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
Kris Wallsmith
 
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and Simple
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and SimpleDrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and Simple
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and Simple
Alexander Varwijk
 
Drupal 8 Sample Module
Drupal 8 Sample ModuleDrupal 8 Sample Module
Drupal 8 Sample Module
drubb
 
Drupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdfDrupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdf
Luca Lusso
 
2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pages2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pages
sparkfabrik
 
Drupal 8 Every Day: An Intro to Developing With Drupal 8
Drupal 8 Every Day: An Intro to Developing With Drupal 8Drupal 8 Every Day: An Intro to Developing With Drupal 8
Drupal 8 Every Day: An Intro to Developing With Drupal 8
Acquia
 
D8 Form api
D8 Form apiD8 Form api
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency Injection
Philip Norton
 
Routing in Drupal 8
Routing in Drupal 8Routing in Drupal 8
Routing in Drupal 8
kgoel1
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
Jeroen van Dijk
 
The new form framework
The new form frameworkThe new form framework
The new form framework
Bernhard Schussek
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injection
Josh Adell
 

Similar to Михаил Крайнюк - Form API + Drupal 8: Form and AJAX (20)

Mikhail Kraynuk. Form api. Drupal 8
Mikhail Kraynuk. Form api. Drupal 8Mikhail Kraynuk. Form api. Drupal 8
Mikhail Kraynuk. Form api. Drupal 8
 
Mikhail Kraynuk. Form api. Drupal 8
Mikhail Kraynuk. Form api. Drupal 8Mikhail Kraynuk. Form api. Drupal 8
Mikhail Kraynuk. Form api. Drupal 8
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Forms
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
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
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and Simple
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and SimpleDrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and Simple
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and Simple
 
Drupal 8 Sample Module
Drupal 8 Sample ModuleDrupal 8 Sample Module
Drupal 8 Sample Module
 
Drupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdfDrupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdf
 
2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pages2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pages
 
Drupal 8 Every Day: An Intro to Developing With Drupal 8
Drupal 8 Every Day: An Intro to Developing With Drupal 8Drupal 8 Every Day: An Intro to Developing With Drupal 8
Drupal 8 Every Day: An Intro to Developing With Drupal 8
 
D8 Form api
D8 Form apiD8 Form api
D8 Form api
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency Injection
 
Routing in Drupal 8
Routing in Drupal 8Routing in Drupal 8
Routing in Drupal 8
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 
The new form framework
The new form frameworkThe new form framework
The new form framework
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injection
 

More from DrupalSib

SSO авторизация - Татьяна Киселева, DrupalJedi
SSO авторизация - Татьяна Киселева, DrupalJediSSO авторизация - Татьяна Киселева, DrupalJedi
SSO авторизация - Татьяна Киселева, DrupalJedi
DrupalSib
 
XML в крупных размерах - Михаил Крайнюк, DrupalJedi
XML в крупных размерах - Михаил Крайнюк, DrupalJediXML в крупных размерах - Михаил Крайнюк, DrupalJedi
XML в крупных размерах - Михаил Крайнюк, DrupalJedi
DrupalSib
 
BigPipe: ускоряем загрузку страниц - Давид Пашаев, DrupalJedi
BigPipe: ускоряем загрузку страниц - Давид Пашаев, DrupalJediBigPipe: ускоряем загрузку страниц - Давид Пашаев, DrupalJedi
BigPipe: ускоряем загрузку страниц - Давид Пашаев, DrupalJedi
DrupalSib
 
Drupal в школе - Борис Шрайнер
Drupal в школе - Борис ШрайнерDrupal в школе - Борис Шрайнер
Drupal в школе - Борис Шрайнер
DrupalSib
 
Евгений Юдкин - Коммуникационные инструменты в отделе продаж на примере интег...
Евгений Юдкин - Коммуникационные инструменты в отделе продаж на примере интег...Евгений Юдкин - Коммуникационные инструменты в отделе продаж на примере интег...
Евгений Юдкин - Коммуникационные инструменты в отделе продаж на примере интег...
DrupalSib
 
D8 - Serialize, Normalize - Михаил Крайнюк, DrupalJedi
D8 - Serialize, Normalize - Михаил Крайнюк, DrupalJediD8 - Serialize, Normalize - Михаил Крайнюк, DrupalJedi
D8 - Serialize, Normalize - Михаил Крайнюк, DrupalJedi
DrupalSib
 
Drupal - создание инсталляционных профайлов - Иван Абраменко, CimpleO
Drupal - создание инсталляционных профайлов - Иван Абраменко, CimpleODrupal - создание инсталляционных профайлов - Иван Абраменко, CimpleO
Drupal - создание инсталляционных профайлов - Иван Абраменко, CimpleO
DrupalSib
 
Вадим Валуев - Искусство ИТ
Вадим Валуев - Искусство ИТВадим Валуев - Искусство ИТ
Вадим Валуев - Искусство ИТ
DrupalSib
 
Андрей Юртаев - Mastering Views
Андрей Юртаев - Mastering ViewsАндрей Юртаев - Mastering Views
Андрей Юртаев - Mastering Views
DrupalSib
 
Migrate drupal 6 to drupal 8. Абраменко Иван
Migrate drupal 6 to drupal 8.  Абраменко ИванMigrate drupal 6 to drupal 8.  Абраменко Иван
Migrate drupal 6 to drupal 8. Абраменко Иван
DrupalSib
 
Entity возрождение легенды. Исай Руслан
Entity возрождение легенды. Исай РусланEntity возрождение легенды. Исай Руслан
Entity возрождение легенды. Исай Руслан
DrupalSib
 
возводим динамическую таблицу, No views, no problem. Крайнюк Михаил
возводим динамическую таблицу, No views, no problem. Крайнюк Михаилвозводим динамическую таблицу, No views, no problem. Крайнюк Михаил
возводим динамическую таблицу, No views, no problem. Крайнюк Михаил
DrupalSib
 
Реализация “гибких” списков Жамбалова Намжилма
Реализация “гибких” списков Жамбалова Намжилма Реализация “гибких” списков Жамбалова Намжилма
Реализация “гибких” списков Жамбалова Намжилма
DrupalSib
 
Петр Селфин. Шок! Drupal 8 против SEO?! Без регистрации и SMS скачать бесплатно
Петр Селфин. Шок! Drupal 8 против SEO?! Без регистрации и SMS скачать бесплатноПетр Селфин. Шок! Drupal 8 против SEO?! Без регистрации и SMS скачать бесплатно
Петр Селфин. Шок! Drupal 8 против SEO?! Без регистрации и SMS скачать бесплатно
DrupalSib
 
Сергей Синица. Разработка интернет-магазинов на Drupal
Сергей Синица. Разработка интернет-магазинов на DrupalСергей Синица. Разработка интернет-магазинов на Drupal
Сергей Синица. Разработка интернет-магазинов на Drupal
DrupalSib
 
Eugene Ilyin. Why Drupal is cool?
Eugene Ilyin. Why Drupal is cool?Eugene Ilyin. Why Drupal is cool?
Eugene Ilyin. Why Drupal is cool?
DrupalSib
 
Ivan Kotlyar. PostgreSQL in web applications
Ivan Kotlyar. PostgreSQL in web applicationsIvan Kotlyar. PostgreSQL in web applications
Ivan Kotlyar. PostgreSQL in web applications
DrupalSib
 
Sergey Cherebedov. Deployment of the environment for Drupal using Ansible.
Sergey Cherebedov. Deployment of the environment for Drupal using Ansible.Sergey Cherebedov. Deployment of the environment for Drupal using Ansible.
Sergey Cherebedov. Deployment of the environment for Drupal using Ansible.
DrupalSib
 
Anton Shloma. Drupal as an integration platform
Anton Shloma. Drupal as an integration platformAnton Shloma. Drupal as an integration platform
Anton Shloma. Drupal as an integration platform
DrupalSib
 
Руслан Исай - Проповедуем Drupal разработку
Руслан Исай - Проповедуем Drupal разработку Руслан Исай - Проповедуем Drupal разработку
Руслан Исай - Проповедуем Drupal разработку
DrupalSib
 

More from DrupalSib (20)

SSO авторизация - Татьяна Киселева, DrupalJedi
SSO авторизация - Татьяна Киселева, DrupalJediSSO авторизация - Татьяна Киселева, DrupalJedi
SSO авторизация - Татьяна Киселева, DrupalJedi
 
XML в крупных размерах - Михаил Крайнюк, DrupalJedi
XML в крупных размерах - Михаил Крайнюк, DrupalJediXML в крупных размерах - Михаил Крайнюк, DrupalJedi
XML в крупных размерах - Михаил Крайнюк, DrupalJedi
 
BigPipe: ускоряем загрузку страниц - Давид Пашаев, DrupalJedi
BigPipe: ускоряем загрузку страниц - Давид Пашаев, DrupalJediBigPipe: ускоряем загрузку страниц - Давид Пашаев, DrupalJedi
BigPipe: ускоряем загрузку страниц - Давид Пашаев, DrupalJedi
 
Drupal в школе - Борис Шрайнер
Drupal в школе - Борис ШрайнерDrupal в школе - Борис Шрайнер
Drupal в школе - Борис Шрайнер
 
Евгений Юдкин - Коммуникационные инструменты в отделе продаж на примере интег...
Евгений Юдкин - Коммуникационные инструменты в отделе продаж на примере интег...Евгений Юдкин - Коммуникационные инструменты в отделе продаж на примере интег...
Евгений Юдкин - Коммуникационные инструменты в отделе продаж на примере интег...
 
D8 - Serialize, Normalize - Михаил Крайнюк, DrupalJedi
D8 - Serialize, Normalize - Михаил Крайнюк, DrupalJediD8 - Serialize, Normalize - Михаил Крайнюк, DrupalJedi
D8 - Serialize, Normalize - Михаил Крайнюк, DrupalJedi
 
Drupal - создание инсталляционных профайлов - Иван Абраменко, CimpleO
Drupal - создание инсталляционных профайлов - Иван Абраменко, CimpleODrupal - создание инсталляционных профайлов - Иван Абраменко, CimpleO
Drupal - создание инсталляционных профайлов - Иван Абраменко, CimpleO
 
Вадим Валуев - Искусство ИТ
Вадим Валуев - Искусство ИТВадим Валуев - Искусство ИТ
Вадим Валуев - Искусство ИТ
 
Андрей Юртаев - Mastering Views
Андрей Юртаев - Mastering ViewsАндрей Юртаев - Mastering Views
Андрей Юртаев - Mastering Views
 
Migrate drupal 6 to drupal 8. Абраменко Иван
Migrate drupal 6 to drupal 8.  Абраменко ИванMigrate drupal 6 to drupal 8.  Абраменко Иван
Migrate drupal 6 to drupal 8. Абраменко Иван
 
Entity возрождение легенды. Исай Руслан
Entity возрождение легенды. Исай РусланEntity возрождение легенды. Исай Руслан
Entity возрождение легенды. Исай Руслан
 
возводим динамическую таблицу, No views, no problem. Крайнюк Михаил
возводим динамическую таблицу, No views, no problem. Крайнюк Михаилвозводим динамическую таблицу, No views, no problem. Крайнюк Михаил
возводим динамическую таблицу, No views, no problem. Крайнюк Михаил
 
Реализация “гибких” списков Жамбалова Намжилма
Реализация “гибких” списков Жамбалова Намжилма Реализация “гибких” списков Жамбалова Намжилма
Реализация “гибких” списков Жамбалова Намжилма
 
Петр Селфин. Шок! Drupal 8 против SEO?! Без регистрации и SMS скачать бесплатно
Петр Селфин. Шок! Drupal 8 против SEO?! Без регистрации и SMS скачать бесплатноПетр Селфин. Шок! Drupal 8 против SEO?! Без регистрации и SMS скачать бесплатно
Петр Селфин. Шок! Drupal 8 против SEO?! Без регистрации и SMS скачать бесплатно
 
Сергей Синица. Разработка интернет-магазинов на Drupal
Сергей Синица. Разработка интернет-магазинов на DrupalСергей Синица. Разработка интернет-магазинов на Drupal
Сергей Синица. Разработка интернет-магазинов на Drupal
 
Eugene Ilyin. Why Drupal is cool?
Eugene Ilyin. Why Drupal is cool?Eugene Ilyin. Why Drupal is cool?
Eugene Ilyin. Why Drupal is cool?
 
Ivan Kotlyar. PostgreSQL in web applications
Ivan Kotlyar. PostgreSQL in web applicationsIvan Kotlyar. PostgreSQL in web applications
Ivan Kotlyar. PostgreSQL in web applications
 
Sergey Cherebedov. Deployment of the environment for Drupal using Ansible.
Sergey Cherebedov. Deployment of the environment for Drupal using Ansible.Sergey Cherebedov. Deployment of the environment for Drupal using Ansible.
Sergey Cherebedov. Deployment of the environment for Drupal using Ansible.
 
Anton Shloma. Drupal as an integration platform
Anton Shloma. Drupal as an integration platformAnton Shloma. Drupal as an integration platform
Anton Shloma. Drupal as an integration platform
 
Руслан Исай - Проповедуем Drupal разработку
Руслан Исай - Проповедуем Drupal разработку Руслан Исай - Проповедуем Drupal разработку
Руслан Исай - Проповедуем Drupal разработку
 

Recently uploaded

How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
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
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
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
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 
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
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
jpupo2018
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
David Brossard
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 

Recently uploaded (20)

How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
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
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
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)
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 
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
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 

Михаил Крайнюк - Form API + Drupal 8: Form and AJAX

  • 1. FormAPI + Drupal 8 Form and AJAX Mikhail Kraynuk
  • 2. Mikhail Kraynuk Drupal Senior Developer About my experience in Drupal development ●  Development ●  Project management ●  Drupal audit ●  Drupal Localization
  • 3. Mikhail Kraynuk Drupal Senior Developer Form API Drupal 8 OK Class namespase function Object-oriented programming extends use
  • 4. Mikhail Kraynuk Drupal Senior Developer New Form <?php     /**     *  @file     *  Contains  DrupalExampleFormExampleForm.     */       namespace  DrupalexampleForm;     use  DrupalCoreFormFormBase;     use  DrupalCoreFormFormStateInterface;       /**     *  Provides  a  simple  example  form.     */     class  ExampleForm  extends  FormBase  {       }   public function getFormID() public function buildForm($form, $form_state) public function validateForm(&$form, $form_state) public function submitForm(&$form, &$form_state)
  • 5. Mikhail Kraynuk Drupal Senior Developer Form ID /**      *  Implements  DrupalCoreFormFormInterface::getFormID().      */   public  function  getFormID()  {        return  ’my_special_form’;   }     /**      *  Form  builder  for  my  form.      */   function  my_special_form($form,  &$form_state)  {…} Drupal 7
  • 6. Mikhail Kraynuk Drupal Senior Developer Form builder /**      *  Implements  DrupalCoreFormFormInterface::buildForm().      */   public  function  buildForm(array  $form,  FormStateInterface  $form_state,  $a  =  0)  {          $form['my_text_field']  =  array(          '#type'  =>  'textfield',          '#title'  =>  'Example',      );        return  $form;     }    
  • 7. Mikhail Kraynuk Drupal Senior Developer Form validate /**      *  Implements  DrupalCoreFormFormInterface::validateForm().      */   public  function  validateForm(array  &$form,  FormStateInterface  $form_state)  {       if (strlen($form_state-­‐>getValue('phone_number')) < 3) { $form_state-­‐>setErrorByName('phone_number', $this-­‐>t('The phone number is too short.')); }   }    
  • 8. Mikhail Kraynuk Drupal Senior Developer Form submit /**      *  Implements  DrupalCoreFormFormInterface::submitForm().      */   public  function  submitForm(array  &$form,  FormStateInterface  $form_state)  {          $phone  =  $form_state-­‐>getValue('phone_number');     }      
  • 9. Mikhail Kraynuk Drupal Senior Developer Get form $form  =  Drupal::formBuilder()-­‐>getForm('DrupalExampleFormExampleForm');           $form  =  Drupal::formBuilder()-­‐>getForm('DrupalExampleFormExampleForm',  'test');  
  • 10. Mikhail Kraynuk Drupal Senior Developer Special forms
  • 11. Mikhail Kraynuk Drupal Senior Developer Settings form use  DrupalCoreFormFormBase;   use  DrupalCoreFormConfigFormBase;     class  ExampleConfigForm  extends  ConfigFormBase  {     ...      public  function  buildForm(array  $form,  FormStateInterface  $form_state)  {            $form  =  parent::buildForm($form,  $form_state);            ...          return  $form;        }     ...   }   system_settings_form() Drupal 7
  • 12. Mikhail Kraynuk Drupal Senior Developer Confirm form use  DrupalCoreFormFormBase;   use  DrupalCoreFormConfirmFormBase;     class  ExampleConfigForm  extends  ConfirmFormBase  {     ...      public  function  buildForm(array  $form,  FormStateInterface  $form_state)  {            $form  =  parent::buildForm($form,  $form_state);            ...          return  $form;        }     ...   } confirm_form() Drupal 7
  • 14. Mikhail Kraynuk Drupal Senior Developer AJAX OK OK AJAX AJAX commands
  • 15. Mikhail Kraynuk Drupal Senior Developer 1. Add Ajax namespace <?php     /**     *  @file     *  Contains  DrupalExampleFormExampleForm.     */       namespace  DrupalexampleForm;     use  DrupalCoreFormFormBase;   use  DrupalCoreFormFormStateInterface;       use  DrupalCoreAjaxAjaxResponse;     use  DrupalCoreAjaxHtmlCommand;       /**     *  Provides  a  simple  example  form.     */     class  ExampleForm  extends  FormBase  {  ...  }  
  • 16. Mikhail Kraynuk Drupal Senior Developer 2. Add Ajax-callback /**     *  Provides  a  simple  example  form.     */     class  ExampleForm  extends  FormBase  {        public  function  getFormID()      public  function  buildForm(array  $form,  FormStateInterface  $form_state)      public  function  validateForm(array  &$form,  FormStateInterface  $form_state)      public  function  submitForm(array  &$form,  FormStateInterface  $form_state)        public  function  validateAjaxPhone(array  &$form,  FormStateInterface  $form_state)   }  
  • 17. Mikhail Kraynuk Drupal Senior Developer 3. Update field public  function  buildForm(array  $form,  FormStateInterface  $form_state)  {        ...      $form['my_phone']  =  array(          '#type'  =>  'tel',          '#title'  =>  $this-­‐>t('Phone number'),          '#description'  =>  $this-­‐>t('Enter your phone number with “+”.'),          '#ajax'  =>  array(              'callback'  =>  array($this,  'validateAjaxPhone'),              'event'  =>  'change',              'progress'  =>  array(                  'type'  =>  'throbber',                  'message'  =>  $this-­‐>t('verifying…'),              ),          ),          '#suffix'  =>  '<span  class=“valid-­‐message”></span>',      );      return  $form;     }    
  • 18. Mikhail Kraynuk Drupal Senior Developer 4. Fill Ajax-callback public  function  validateAjaxPhone(array  &$form,  FormStateInterface  $form_state)  {          $response  =  new  AjaxResponse();            if (substr($form_state-­‐>getValue('my_phone'),  0,  1) == '+') {          $message  =  $this-­‐>t('Phone number is correct');      }      else {          $message  =  $this-­‐>t('Please start your phone number with “+”');      }        $response-­‐>addCommand(new  HtmlCommand('.valid-­‐message',  $message));        return  $response;     }    
  • 19. Mikhail Kraynuk Drupal Senior Developer Ajax result
  • 20. Mikhail Kraynuk Drupal Senior Developer Ajax result
  • 21. Mikhail Kraynuk Drupal Senior developer Mikhail Kraynuk Drupal Senior Developer kraynuk.m@i20.biz +7 961 870-26-99 Золотой спонсор: Спасибо! При поддержке: Серебряный спонсор: