SlideShare ist ein Scribd-Unternehmen logo
1 von 24
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of LithiumNate Abele
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Fabien 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.4Fabien Potencier
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium AppsNate Abele
 
Drupal Module Development
Drupal Module DevelopmentDrupal Module Development
Drupal Module Developmentipsitamishra
 
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 FrameworksNate 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 UsageRonald Ashri
 
Entity Query API
Entity Query APIEntity Query API
Entity Query APImarcingy
 
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.3Fabien 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 EditionNate Abele
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comJD Leonard
 
Drupal 8: Theming
Drupal 8: ThemingDrupal 8: Theming
Drupal 8: Themingdrubb
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2zfconfua
 

Was ist angesagt? (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
 

Andere mochten auch

Drupal 8: TWIG Template Engine
Drupal 8:  TWIG Template EngineDrupal 8:  TWIG Template Engine
Drupal 8: TWIG Template Enginedrubb
 
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 StartAcquia
 
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 2015Dropsolid
 
Drupal 8 templating with twig
Drupal 8 templating with twigDrupal 8 templating with twig
Drupal 8 templating with twigTaras Omelianenko
 
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 2017Michael 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 OverviewItalo 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 8Anne Tomasevich
 
RESTful application with Drupal 8
RESTful application with Drupal 8RESTful application with Drupal 8
RESTful application with Drupal 8Patrick Morin
 

Andere mochten auch (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
 

Ähnlich wie 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 AJAXDrupalSib
 
Mikhail Kraynuk. Form api. Drupal 8
Mikhail Kraynuk. Form api. Drupal 8Mikhail Kraynuk. Form api. Drupal 8
Mikhail Kraynuk. Form api. Drupal 8i20 Group
 
Mikhail Kraynuk. Form api. Drupal 8
Mikhail Kraynuk. Form api. Drupal 8Mikhail Kraynuk. Form api. Drupal 8
Mikhail Kraynuk. Form api. Drupal 8DrupalSib
 
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 8kgoel1
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful softwareJorn Oomen
 
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
 
WordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta BoxesWordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta BoxesJeremy Green
 
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
 
Drupal csu-open atriumname
Drupal csu-open atriumnameDrupal csu-open atriumname
Drupal csu-open atriumnameEmanuele Quinto
 
14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilor14. CodeIgniter adaugarea inregistrarilor
14. CodeIgniter adaugarea inregistrarilorRazvan Raducanu, PhD
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony AppsKris Wallsmith
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your CodeAbbas Ali
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)Jeff Eaton
 

Ähnlich wie 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
 
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
 
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)
 

Mehr von drubb

Barrierefreie Webseiten
Barrierefreie WebseitenBarrierefreie Webseiten
Barrierefreie Webseitendrubb
 
Drupal 9 Entity Bundle Classes
Drupal 9 Entity Bundle ClassesDrupal 9 Entity Bundle Classes
Drupal 9 Entity Bundle Classesdrubb
 
Drupal 8 Dependency Injection Using Traits
Drupal 8 Dependency Injection Using TraitsDrupal 8 Dependency Injection Using Traits
Drupal 8 Dependency Injection Using Traitsdrubb
 
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 Wodbydrubb
 
Composer & Drupal
Composer & DrupalComposer & Drupal
Composer & Drupaldrubb
 
Headless Drupal
Headless DrupalHeadless Drupal
Headless Drupaldrubb
 
Spamschutzverfahren für Drupal
Spamschutzverfahren für DrupalSpamschutzverfahren für Drupal
Spamschutzverfahren für Drupaldrubb
 
Drupal 8: Neuerungen im Überblick
Drupal 8:  Neuerungen im ÜberblickDrupal 8:  Neuerungen im Überblick
Drupal 8: Neuerungen im Überblickdrubb
 
Drupal Entities
Drupal EntitiesDrupal Entities
Drupal Entitiesdrubb
 

Mehr von 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
 

Kürzlich hochgeladen

定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一z xss
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一Fs
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Sonam Pathan
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书rnrncn29
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Paul Calvano
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxDyna Gilbert
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Excelmac1
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationLinaWolf1
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书rnrncn29
 
Intellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptxIntellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptxBipin Adhikari
 

Kürzlich hochgeladen (20)

定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptx
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 Documentation
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
 
Intellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptxIntellectual property rightsand its types.pptx
Intellectual property rightsand its types.pptx
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 

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