SlideShare a Scribd company logo
Drupal 8: FormsDrupal 8: Forms
Working with forms in Drupal 8 modulesWorking with forms in Drupal 8 modules
Drupal Meetup StuttgartDrupal Meetup Stuttgart
05/07/2015
1. Creating a form1. Creating a form
<?php
/**
* @file
* Contains DrupalconfigFormConfigExportForm.
*/
namespace DrupalconfigForm;
use DrupalCoreFormFormBase;
use DrupalCoreFormFormStateInterface;
class ConfigExportForm extends FormBase {
public function getFormId() {
return 'config_export_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['description'] = array(
...
);
...
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
...
}
}
Example: /modules/config/src/Form/ConfigExportForm.php
FormsForms
are classes
extending base forms
implementing parent methods / properties
using the Drupal Form API
Examples for base formsExamples for base forms
FormBase (generic)
ConfigFormBase (settings forms)
ConfirmFormBase (confirmation forms)
XYZFormBase (roll your own)
<?php
/**
* @file
* Contains DrupalconfigFormConfigExportForm.
*/
namespace DrupalconfigForm;
use DrupalCoreFormFormBase;
use DrupalCoreFormFormStateInterface;
class ConfigExportForm extends FormBase {
public function getFormId() {
return 'config_export_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['description'] = array(
'#markup' => '<p>' . $this->t('Use the export button below to download your site configuration.') . '</p>',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Export'),
);
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$form_state->setRedirect('config.export_download');
}
}
Complete class: DrupalconfigFormConfigExportForm
2. Rendering a form2. Rendering a form
ban.delete:
path: '/admin/config/people/ban/delete/{ban_id}'
defaults:
_form: 'DrupalbanFormBanDelete'
_title: 'Delete IP address'
requirements:
_permission: 'ban IP addresses'
ban.routing.yml
<?php
namespace DrupalbanForm;
use DrupalCoreFormConfirmFormBase;
...
class BanDelete extends ConfirmFormBase {
...
}
Rendering a standalone form on a page
BanDelete.php
...
public function translatePage() {
return array(
'filter' => $this->formBuilder()->getForm('DrupallocaleFormTranslateFilterForm'),
'form' => $this->formBuilder()->getForm('DrupallocaleFormTranslateEditForm'),
);
}
...
DrupallocaleControllerlocaleContoller
<?php
namespace DrupallocaleForm;
use DrupalCoreFormFormStateInterface;
class TranslateFilterForm extends TranslateFormBase {
...
}
Embedding a form in other markup
DrupallocaleFormTranslateFilterForm
3. Validating a form3. Validating a form
Validate =Validate =
Checking form values
Create error messages
Prepare for form submission
...
public function validateForm(array &$form, FormStateInterface $form_state) {
$this->file = file_save_upload('file', $form['file']['#upload_validators'], 'translations://', 0);
// Ensure we have the file uploaded.
if (!$this->file) {
$form_state->setErrorByName('file', $this->t('File to import not found.'))
}
}
Example: DrupallocaleFormImportForm
public function validateForm(array &$form, FormStateInterface $form_state) {
$name = trim($form_state->getValue('name'));
// Try to load by email.
$users = $this->userStorage->loadByProperties(array('mail' => $name, 'status' => '1'));
if (empty($users)) {
// No success, try to load by name.
$users = $this->userStorage->loadByProperties(array('name' => $name, 'status' => '1'));
}
$account = reset($users);
if ($account && $account->id()) {
$form_state->setValueForElement(array('#parents' => array('account')), $account);
}
else {
$form_state->setErrorByName('name', $this->t('Sorry, %name is not recognized as a
username or an email address.', array('%name' => $name)));
}
}
Example: DrupaluserFormUserPasswordForm
4. Submitting a form4. Submitting a form
Submit =Submit =
Storing form values
Output messages
Write log information
Redirect to new URL
...
public function submitForm(array &$form, FormStateInterface $form_state) {
if ($form_state->getValue('confirm')) {
$this->commentStorage->delete($this->comments);
$count = count($form_state->getValue('comments'));
$this->logger('content')->notice('Deleted @count comments.', array('@count' => $count));
drupal_set_message($this->formatPlural($count, 'Deleted 1 comment.', 'Deleted @count comments.'));
}
$form_state->setRedirectUrl($this->getCancelUrl());
}
Example: DrupalcommentFormConfirmDeleteMultiple
public function submitForm(array &$form, FormStateInterface $form_state) {
$allowed_types = array_filter($form_state->getValue('book_allowed_types'));
// We need to save the allowed types in an array ordered by machine_name so
// that we can save them in the correct order if node type changes.
// @see book_node_type_update().
sort($allowed_types);
$this->config('book.settings')
// Remove unchecked types.
->set('allowed_types', $allowed_types)
->set('child_type', $form_state->getValue('book_child_type'))
->save();
parent::submitForm($form, $form_state);
}
Example: DrupalbookFormBookSettingsForm
5. Reusing existing forms5. Reusing existing forms
Reuse =Reuse =
Create a new form based on an existing form
<?php
/**
* @file
* Contains DrupalblockFormBlockDeleteForm.
*/
namespace DrupalblockForm;
use DrupalCoreEntityEntityDeleteForm;
use DrupalCoreUrl;
/**
* Provides a deletion confirmation form for the block instance deletion form.
*/
class BlockDeleteForm extends EntityDeleteForm {
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('block.admin_display');
}
}
Example: DrupalblockFormBlockDeleteForm
6. Modifying forms6. Modifying forms
Some old friends:Some old friends:
hook_form_alter()
hook_form_FORM_ID_alter()
hook_form_BASE_FORM_ID_alter()
...
use DrupalCoreFormFormStateInterface;
...
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Add a checkbox to the node form about agreeing to terms of use.
$form['terms_of_use'] = array(
'#type' => 'checkbox',
'#title' => t("I agree with the website's terms and conditions."),
'#required' => TRUE,
);
}
Example: mymodule.module
Thank You!Thank You!
http://slides.com/drubb
http://slideshare.net/drubb

More Related Content

What's hot

The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
Nate Abele
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
Nate Abele
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
Fabien Potencier
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
Fabien Potencier
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
Nate Abele
 
Drupal Module Development
Drupal Module DevelopmentDrupal Module Development
Drupal Module Development
ipsitamishra
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
Nate Abele
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Fabien Potencier
 
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
 
Entity Query API
Entity Query APIEntity Query API
Entity Query API
marcingy
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
Fabien Potencier
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Nate Abele
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
JD Leonard
 
Drupal 8: Theming
Drupal 8: ThemingDrupal 8: Theming
Drupal 8: Theming
drubb
 
Build your own entity with Drupal
Build your own entity with DrupalBuild your own entity with Drupal
Build your own entity with Drupal
Marco Vito Moscaritolo
 
Drupal 8 Hooks
Drupal 8 HooksDrupal 8 Hooks
Field api.From d7 to d8
Field api.From d7 to d8Field api.From d7 to d8
Field api.From d7 to d8
Pavel Makhrinsky
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
Nate Abele
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
zfconfua
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
Richard McIntyre
 

What's hot (20)

The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
Drupal Module Development
Drupal Module DevelopmentDrupal Module Development
Drupal Module Development
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
 
Drupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of UsageDrupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of Usage
 
Entity Query API
Entity Query APIEntity Query API
Entity Query API
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
 
Drupal 8: Theming
Drupal 8: ThemingDrupal 8: Theming
Drupal 8: Theming
 
Build your own entity with Drupal
Build your own entity with DrupalBuild your own entity with Drupal
Build your own entity with Drupal
 
Drupal 8 Hooks
Drupal 8 HooksDrupal 8 Hooks
Drupal 8 Hooks
 
Field api.From d7 to d8
Field api.From d7 to d8Field api.From d7 to d8
Field api.From d7 to d8
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
 

Viewers also liked

Drupal 8: TWIG Template Engine
Drupal 8:  TWIG Template EngineDrupal 8:  TWIG Template Engine
Drupal 8: TWIG Template Engine
drubb
 
Preventing Drupal Headaches: Establishing Flexible File Paths From The Start
Preventing Drupal Headaches: Establishing Flexible File Paths From The StartPreventing Drupal Headaches: Establishing Flexible File Paths From The Start
Preventing Drupal Headaches: Establishing Flexible File Paths From The Start
Acquia
 
State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015
State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015
State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015
Dropsolid
 
Drupal 8 templating with twig
Drupal 8 templating with twigDrupal 8 templating with twig
Drupal 8 templating with twig
Taras Omelianenko
 
Drupal 7 and SolR
Drupal 7 and SolRDrupal 7 and SolR
Drupal 7 and SolR
Patrick Morin
 
The Flexibility of Drupal 8 | DCNLights 2017
The Flexibility of Drupal 8 | DCNLights 2017The Flexibility of Drupal 8 | DCNLights 2017
The Flexibility of Drupal 8 | DCNLights 2017
Michael Miles
 
From Drupal 7 to Drupal 8 - Drupal Intensive Course Overview
From Drupal 7 to Drupal 8 - Drupal Intensive Course OverviewFrom Drupal 7 to Drupal 8 - Drupal Intensive Course Overview
From Drupal 7 to Drupal 8 - Drupal Intensive Course Overview
Italo Mairo
 
Building a Custom Theme in Drupal 8
Building a Custom Theme in Drupal 8Building a Custom Theme in Drupal 8
Building a Custom Theme in Drupal 8
Anne Tomasevich
 
RESTful application with Drupal 8
RESTful application with Drupal 8RESTful application with Drupal 8
RESTful application with Drupal 8
Patrick Morin
 

Viewers also liked (9)

Drupal 8: TWIG Template Engine
Drupal 8:  TWIG Template EngineDrupal 8:  TWIG Template Engine
Drupal 8: TWIG Template Engine
 
Preventing Drupal Headaches: Establishing Flexible File Paths From The Start
Preventing Drupal Headaches: Establishing Flexible File Paths From The StartPreventing Drupal Headaches: Establishing Flexible File Paths From The Start
Preventing Drupal Headaches: Establishing Flexible File Paths From The Start
 
State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015
State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015
State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015
 
Drupal 8 templating with twig
Drupal 8 templating with twigDrupal 8 templating with twig
Drupal 8 templating with twig
 
Drupal 7 and SolR
Drupal 7 and SolRDrupal 7 and SolR
Drupal 7 and SolR
 
The Flexibility of Drupal 8 | DCNLights 2017
The Flexibility of Drupal 8 | DCNLights 2017The Flexibility of Drupal 8 | DCNLights 2017
The Flexibility of Drupal 8 | DCNLights 2017
 
From Drupal 7 to Drupal 8 - Drupal Intensive Course Overview
From Drupal 7 to Drupal 8 - Drupal Intensive Course OverviewFrom Drupal 7 to Drupal 8 - Drupal Intensive Course Overview
From Drupal 7 to Drupal 8 - Drupal Intensive Course Overview
 
Building a Custom Theme in Drupal 8
Building a Custom Theme in Drupal 8Building a Custom Theme in Drupal 8
Building a Custom Theme in Drupal 8
 
RESTful application with Drupal 8
RESTful application with Drupal 8RESTful application with Drupal 8
RESTful application with Drupal 8
 

Similar to Drupal 8: Forms

Михаил Крайнюк - 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
 
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
 
D8 Form api
D8 Form apiD8 Form api
Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)
Arnaud Langlade
 
Routing in Drupal 8
Routing in Drupal 8Routing in Drupal 8
Routing in Drupal 8
kgoel1
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
Jorn Oomen
 
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
 
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
 
Moodle Quick Forms
Moodle Quick FormsMoodle Quick Forms
Moodle Quick Forms
Jalpa Bhavsar
 
Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?
Julien Vinber
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
Lars Jankowfsky
 
Drupal csu-open atriumname
Drupal csu-open atriumnameDrupal csu-open atriumname
Drupal csu-open atriumname
Emanuele Quinto
 
Framework
FrameworkFramework
Framework
Nguyen Linh
 
14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilor14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilor
Razvan Raducanu, PhD
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
Kris Wallsmith
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your Code
Abbas Ali
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
Jeff Eaton
 

Similar to Drupal 8: Forms (20)

Михаил Крайнюк - 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
 
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
 
D8 Form api
D8 Form apiD8 Form api
D8 Form api
 
Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)
 
Routing in Drupal 8
Routing in Drupal 8Routing in Drupal 8
Routing in Drupal 8
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
 
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
 
WordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta BoxesWordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta Boxes
 
Moodle Quick Forms
Moodle Quick FormsMoodle Quick Forms
Moodle Quick Forms
 
Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?Et si on en finissait avec CRUD ?
Et si on en finissait avec CRUD ?
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Drupal csu-open atriumname
Drupal csu-open atriumnameDrupal csu-open atriumname
Drupal csu-open atriumname
 
Framework
FrameworkFramework
Framework
 
14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilor14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilor
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your Code
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
 

More from drubb

Barrierefreie Webseiten
Barrierefreie WebseitenBarrierefreie Webseiten
Barrierefreie Webseiten
drubb
 
Drupal 9 Entity Bundle Classes
Drupal 9 Entity Bundle ClassesDrupal 9 Entity Bundle Classes
Drupal 9 Entity Bundle Classes
drubb
 
Drupal 8 Dependency Injection Using Traits
Drupal 8 Dependency Injection Using TraitsDrupal 8 Dependency Injection Using Traits
Drupal 8 Dependency Injection Using Traits
drubb
 
Closing the Drupal Hosting Gap - A Review of Wodby
Closing the Drupal Hosting Gap - A Review of WodbyClosing the Drupal Hosting Gap - A Review of Wodby
Closing the Drupal Hosting Gap - A Review of Wodby
drubb
 
Composer & Drupal
Composer & DrupalComposer & Drupal
Composer & Drupal
drubb
 
Headless Drupal
Headless DrupalHeadless Drupal
Headless Drupal
drubb
 
Spamschutzverfahren für Drupal
Spamschutzverfahren für DrupalSpamschutzverfahren für Drupal
Spamschutzverfahren für Drupal
drubb
 
Drupal 8: Neuerungen im Überblick
Drupal 8:  Neuerungen im ÜberblickDrupal 8:  Neuerungen im Überblick
Drupal 8: Neuerungen im Überblick
drubb
 
Drupal Entities
Drupal EntitiesDrupal Entities
Drupal Entities
drubb
 

More from drubb (9)

Barrierefreie Webseiten
Barrierefreie WebseitenBarrierefreie Webseiten
Barrierefreie Webseiten
 
Drupal 9 Entity Bundle Classes
Drupal 9 Entity Bundle ClassesDrupal 9 Entity Bundle Classes
Drupal 9 Entity Bundle Classes
 
Drupal 8 Dependency Injection Using Traits
Drupal 8 Dependency Injection Using TraitsDrupal 8 Dependency Injection Using Traits
Drupal 8 Dependency Injection Using Traits
 
Closing the Drupal Hosting Gap - A Review of Wodby
Closing the Drupal Hosting Gap - A Review of WodbyClosing the Drupal Hosting Gap - A Review of Wodby
Closing the Drupal Hosting Gap - A Review of Wodby
 
Composer & Drupal
Composer & DrupalComposer & Drupal
Composer & Drupal
 
Headless Drupal
Headless DrupalHeadless Drupal
Headless Drupal
 
Spamschutzverfahren für Drupal
Spamschutzverfahren für DrupalSpamschutzverfahren für Drupal
Spamschutzverfahren für Drupal
 
Drupal 8: Neuerungen im Überblick
Drupal 8:  Neuerungen im ÜberblickDrupal 8:  Neuerungen im Überblick
Drupal 8: Neuerungen im Überblick
 
Drupal Entities
Drupal EntitiesDrupal Entities
Drupal Entities
 

Recently uploaded

怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
rtunex8r
 
[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024
hackersuli
 
Gen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needsGen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needs
Laura Szabó
 
Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?
Paul Walk
 
办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理
办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理
办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理
uehowe
 
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
fovkoyb
 
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
xjq03c34
 
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
k4ncd0z
 
Design Thinking NETFLIX using all techniques.pptx
Design Thinking NETFLIX using all techniques.pptxDesign Thinking NETFLIX using all techniques.pptx
Design Thinking NETFLIX using all techniques.pptx
saathvikreddy2003
 
留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理
留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理
留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理
uehowe
 
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
uehowe
 
HijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process HollowingHijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process Hollowing
Donato Onofri
 
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
bseovas
 
Ready to Unlock the Power of Blockchain!
Ready to Unlock the Power of Blockchain!Ready to Unlock the Power of Blockchain!
Ready to Unlock the Power of Blockchain!
Toptal Tech
 
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
ysasp1
 
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
3a0sd7z3
 
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
3a0sd7z3
 
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaalmanuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
wolfsoftcompanyco
 
Discover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to IndiaDiscover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to India
davidjhones387
 

Recently uploaded (19)

怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
 
[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024
 
Gen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needsGen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needs
 
Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?
 
办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理
办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理
办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理
 
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
 
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
 
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
 
Design Thinking NETFLIX using all techniques.pptx
Design Thinking NETFLIX using all techniques.pptxDesign Thinking NETFLIX using all techniques.pptx
Design Thinking NETFLIX using all techniques.pptx
 
留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理
留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理
留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理
 
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
 
HijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process HollowingHijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process Hollowing
 
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
 
Ready to Unlock the Power of Blockchain!
Ready to Unlock the Power of Blockchain!Ready to Unlock the Power of Blockchain!
Ready to Unlock the Power of Blockchain!
 
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
 
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
 
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
 
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaalmanuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
 
Discover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to IndiaDiscover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to India
 

Drupal 8: Forms

  • 1. Drupal 8: FormsDrupal 8: Forms Working with forms in Drupal 8 modulesWorking with forms in Drupal 8 modules Drupal Meetup StuttgartDrupal Meetup Stuttgart 05/07/2015
  • 2. 1. Creating a form1. Creating a form
  • 3. <?php /** * @file * Contains DrupalconfigFormConfigExportForm. */ namespace DrupalconfigForm; use DrupalCoreFormFormBase; use DrupalCoreFormFormStateInterface; class ConfigExportForm extends FormBase { public function getFormId() { return 'config_export_form'; } public function buildForm(array $form, FormStateInterface $form_state) { $form['description'] = array( ... ); ... return $form; } public function submitForm(array &$form, FormStateInterface $form_state) { ... } } Example: /modules/config/src/Form/ConfigExportForm.php
  • 4. FormsForms are classes extending base forms implementing parent methods / properties using the Drupal Form API
  • 5. Examples for base formsExamples for base forms FormBase (generic) ConfigFormBase (settings forms) ConfirmFormBase (confirmation forms) XYZFormBase (roll your own)
  • 6. <?php /** * @file * Contains DrupalconfigFormConfigExportForm. */ namespace DrupalconfigForm; use DrupalCoreFormFormBase; use DrupalCoreFormFormStateInterface; class ConfigExportForm extends FormBase { public function getFormId() { return 'config_export_form'; } public function buildForm(array $form, FormStateInterface $form_state) { $form['description'] = array( '#markup' => '<p>' . $this->t('Use the export button below to download your site configuration.') . '</p>', ); $form['submit'] = array( '#type' => 'submit', '#value' => $this->t('Export'), ); return $form; } public function submitForm(array &$form, FormStateInterface $form_state) { $form_state->setRedirect('config.export_download'); } } Complete class: DrupalconfigFormConfigExportForm
  • 7. 2. Rendering a form2. Rendering a form
  • 8. ban.delete: path: '/admin/config/people/ban/delete/{ban_id}' defaults: _form: 'DrupalbanFormBanDelete' _title: 'Delete IP address' requirements: _permission: 'ban IP addresses' ban.routing.yml <?php namespace DrupalbanForm; use DrupalCoreFormConfirmFormBase; ... class BanDelete extends ConfirmFormBase { ... } Rendering a standalone form on a page BanDelete.php
  • 9. ... public function translatePage() { return array( 'filter' => $this->formBuilder()->getForm('DrupallocaleFormTranslateFilterForm'), 'form' => $this->formBuilder()->getForm('DrupallocaleFormTranslateEditForm'), ); } ... DrupallocaleControllerlocaleContoller <?php namespace DrupallocaleForm; use DrupalCoreFormFormStateInterface; class TranslateFilterForm extends TranslateFormBase { ... } Embedding a form in other markup DrupallocaleFormTranslateFilterForm
  • 10. 3. Validating a form3. Validating a form
  • 11. Validate =Validate = Checking form values Create error messages Prepare for form submission ...
  • 12. public function validateForm(array &$form, FormStateInterface $form_state) { $this->file = file_save_upload('file', $form['file']['#upload_validators'], 'translations://', 0); // Ensure we have the file uploaded. if (!$this->file) { $form_state->setErrorByName('file', $this->t('File to import not found.')) } } Example: DrupallocaleFormImportForm
  • 13. public function validateForm(array &$form, FormStateInterface $form_state) { $name = trim($form_state->getValue('name')); // Try to load by email. $users = $this->userStorage->loadByProperties(array('mail' => $name, 'status' => '1')); if (empty($users)) { // No success, try to load by name. $users = $this->userStorage->loadByProperties(array('name' => $name, 'status' => '1')); } $account = reset($users); if ($account && $account->id()) { $form_state->setValueForElement(array('#parents' => array('account')), $account); } else { $form_state->setErrorByName('name', $this->t('Sorry, %name is not recognized as a username or an email address.', array('%name' => $name))); } } Example: DrupaluserFormUserPasswordForm
  • 14. 4. Submitting a form4. Submitting a form
  • 15. Submit =Submit = Storing form values Output messages Write log information Redirect to new URL ...
  • 16. public function submitForm(array &$form, FormStateInterface $form_state) { if ($form_state->getValue('confirm')) { $this->commentStorage->delete($this->comments); $count = count($form_state->getValue('comments')); $this->logger('content')->notice('Deleted @count comments.', array('@count' => $count)); drupal_set_message($this->formatPlural($count, 'Deleted 1 comment.', 'Deleted @count comments.')); } $form_state->setRedirectUrl($this->getCancelUrl()); } Example: DrupalcommentFormConfirmDeleteMultiple
  • 17. public function submitForm(array &$form, FormStateInterface $form_state) { $allowed_types = array_filter($form_state->getValue('book_allowed_types')); // We need to save the allowed types in an array ordered by machine_name so // that we can save them in the correct order if node type changes. // @see book_node_type_update(). sort($allowed_types); $this->config('book.settings') // Remove unchecked types. ->set('allowed_types', $allowed_types) ->set('child_type', $form_state->getValue('book_child_type')) ->save(); parent::submitForm($form, $form_state); } Example: DrupalbookFormBookSettingsForm
  • 18. 5. Reusing existing forms5. Reusing existing forms
  • 19. Reuse =Reuse = Create a new form based on an existing form
  • 20. <?php /** * @file * Contains DrupalblockFormBlockDeleteForm. */ namespace DrupalblockForm; use DrupalCoreEntityEntityDeleteForm; use DrupalCoreUrl; /** * Provides a deletion confirmation form for the block instance deletion form. */ class BlockDeleteForm extends EntityDeleteForm { /** * {@inheritdoc} */ public function getCancelUrl() { return new Url('block.admin_display'); } } Example: DrupalblockFormBlockDeleteForm
  • 21. 6. Modifying forms6. Modifying forms
  • 22. Some old friends:Some old friends: hook_form_alter() hook_form_FORM_ID_alter() hook_form_BASE_FORM_ID_alter()
  • 23. ... use DrupalCoreFormFormStateInterface; ... function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) { // Add a checkbox to the node form about agreeing to terms of use. $form['terms_of_use'] = array( '#type' => 'checkbox', '#title' => t("I agree with the website's terms and conditions."), '#required' => TRUE, ); } Example: mymodule.module