SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
Drupal 8: Sample ModuleDrupal 8: Sample Module
Introducing Block Plugins & Configuration FormsIntroducing Block Plugins & Configuration Forms
Drupal Meetup StuttgartDrupal Meetup Stuttgart
03/05/2015
1. Tell Drupal about the1. Tell Drupal about the
modulemodule
name: Temperature
type: module
description: 'Creates a configurable block showing the local temperature'
package: Meetup
version: '1.0.0'
core: '8.x'
modules/custom/temperature/temperature.info.yml
2. Create a simple block2. Create a simple block
pluginplugin
<?php
/**
* @file
* Contains DrupaltemperaturePluginBlockTemperatureBlock.
*/
namespace DrupaltemperaturePluginBlock;
use DrupalCoreBlockBlockBase;
/**
* Provides a 'Temperature' block.
*
* @Block(
* id = "temperature",
* admin_label = @Translation("Local temperature"),
* category = @Translation("Meetup")
* )
*/
class TemperatureBlock extends BlockBase {
public function build() {
return [
'#markup' => 'Seems cold outside!',
];
}
}
modules/custom/temperature/src/Plugin/Block/TemperatureBlock.php
use GuzzleHttpClient;
class TemperatureBlock extends BlockBase {
public function build() {
$city = 'Stuttgart, DE'
$client = new Client();
$response = $client->get("http://api.openweathermap.org/data/2.5/weather?q=$city");
if ($response->getStatusCode() == '200') {
$result = json_decode($response->getBody());
$markup = "Current temperature in<br>$city:<br>";
$markup .= round($result->main->temp - 273.15) . '° C';
}
else {
$markup = 'Sorry, something went wrong!';
}
return [
'#markup' => $markup,
];
}
}
Adding the "real" content
3. Make block instances3. Make block instances
configurableconfigurable
block.settings.temperature:
type: block_settings
label: 'Temperature block'
mapping:
city:
type: string
label: 'City for temperature display'
modules/custom/temperature/config/schema/temperature.schema.yml
use DrupalCoreBlockBlockBase;
use DrupalCoreFormFormStateInterface;
class TemperatureBlock extends BlockBase {
public function build() {
$city = $this->configuration['city'];
...
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['city'] = array(
'#title' => 'Location',
'#type' => 'textfield',
'#default_value' => $this->configuration['city'],
);
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['city'] = $form_state->getValue('city');
$this->blockSubmit($form, $form_state);
}
}
modules/custom/temperature/src/Plugin/Block/TemperatureBlock.php
4. Provide a default4. Provide a default
configurationconfiguration
temperature.settings:
type: mapping
label: 'Temperature settings'
mapping:
city:
type: string
label: 'Default city for temperature display'
block.settings.temperature:
type: block_settings
label: 'Temperature block'
mapping:
city:
type: string
label: 'City for temperature display'
modules/custom/temperature/config/schema/temperature.schema.yml
modules/custom/temperature/config/install/temperature.settings.yml
city: 'Stuttgart,DE'
...
class TemperatureBlock extends BlockBase {
public function defaultConfiguration() {
$config = Drupal::config('temperature.settings')->get();
return $config;
}
public function build() {
...
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['city'] = array(
'#title' => 'Location',
'#type' => 'textfield',
'#default_value' => $this->configuration['city'],
);
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['city'] = $form_state->getValue('city');
$this->blockSubmit($form, $form_state);
}
}
modules/custom/temperature/src/Plugin/Block/TemperatureBlock.php
5. Make default5. Make default
configuration editableconfiguration editable
temperature.settings:
path: '/admin/config/system/temperature'
defaults:
_form: 'DrupaltemperatureFormSettingsForm'
_title: 'Temperature settings'
requirements:
_permission: 'administer site configuration'
modules/custom/temperature/temperature.routing.yml
<?php
/**
* @file
* Contains DrupaltemperatureFormSettingsForm
*/
namespace DrupaltemperatureForm;
use DrupalCoreFormConfigFormBase;
use DrupalCoreFormFormStateInterface;
class SettingsForm extends ConfigFormBase {
public function buildForm(array $form, FormStateInterface $form_state) {
$form = parent::buildForm($form, $form_state);
$form['city'] = [
'#title' => 'Default Location',
'#type' => 'textfield',
'#default_value' => $this->config('temperature.settings')->get('city'),
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->config('temperature.settings')
->set('city', $form_state->getValue('city'))
->save();
parent::submitForm($form, $form_state);
}
protected function getEditableConfigNames() {
return ['temperature.settings'];
}
public function getFormId() {
return 'temperature_settings';
}
}
modules/custom/temperature/src/Form/SettingsForm.php
Thank You!Thank You!
http://slides.com/drubb
http://slideshare.net/drubb

Weitere ähnliche Inhalte

Was ist angesagt?

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
 
Drupal 8: Theming
Drupal 8: ThemingDrupal 8: Theming
Drupal 8: Theming
drubb
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
Fabien Potencier
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2
Fabien Potencier
 
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
 
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
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
Wildan Maulana
 

Was ist angesagt? (20)

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
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Drupal 8: Theming
Drupal 8: ThemingDrupal 8: Theming
Drupal 8: Theming
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2
 
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
 
Drupal 8 Hooks
Drupal 8 HooksDrupal 8 Hooks
Drupal 8 Hooks
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
 
Build your own entity with Drupal
Build your own entity with DrupalBuild your own entity with Drupal
Build your own entity with Drupal
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
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)
 
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
 
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
 
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
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 

Ähnlich wie Drupal 8 Sample Module

Ähnlich wie Drupal 8 Sample Module (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
 
Debugging in drupal 8
Debugging in drupal 8Debugging in drupal 8
Debugging in drupal 8
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
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
 
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
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Rapid Prototyping with PEAR
Rapid Prototyping with PEARRapid Prototyping with PEAR
Rapid Prototyping with PEAR
 
¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Drupal 8 Theme System: The Backend of Frontend
Drupal 8 Theme System: The Backend of FrontendDrupal 8 Theme System: The Backend of Frontend
Drupal 8 Theme System: The Backend of Frontend
 
Ordering System IP2buildclasses.netbeans_automatic_buildO.docx
Ordering System IP2buildclasses.netbeans_automatic_buildO.docxOrdering System IP2buildclasses.netbeans_automatic_buildO.docx
Ordering System IP2buildclasses.netbeans_automatic_buildO.docx
 
Extbase and Beyond
Extbase and BeyondExtbase and Beyond
Extbase and Beyond
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15
 
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
 
Porting adsense module to Drupal 8
Porting adsense module to Drupal 8Porting adsense module to Drupal 8
Porting adsense module to Drupal 8
 
Drupal 9 training ajax
Drupal 9 training ajaxDrupal 9 training ajax
Drupal 9 training ajax
 
Magento 2 | Declarative schema
Magento 2 | Declarative schemaMagento 2 | Declarative schema
Magento 2 | Declarative schema
 

Mehr von drubb (10)

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: TWIG Template Engine
Drupal 8:  TWIG Template EngineDrupal 8:  TWIG Template Engine
Drupal 8: TWIG Template Engine
 
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

Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
soniya singh
 
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLLucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
imonikaupta
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
soniya singh
 
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
soniya singh
 

Kürzlich hochgeladen (20)

Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
 
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
 
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
 
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls DubaiDubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
 
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLLucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
 
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl ServiceRussian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
 
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
 
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
 
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort ServiceBusty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
 
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
 
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
 
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
 
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
Russian Call Girls in %(+971524965298  )#  Call Girls in DubaiRussian Call Girls in %(+971524965298  )#  Call Girls in Dubai
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
 
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirt
 
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
 

Drupal 8 Sample Module

  • 1. Drupal 8: Sample ModuleDrupal 8: Sample Module Introducing Block Plugins & Configuration FormsIntroducing Block Plugins & Configuration Forms Drupal Meetup StuttgartDrupal Meetup Stuttgart 03/05/2015
  • 2. 1. Tell Drupal about the1. Tell Drupal about the modulemodule
  • 3. name: Temperature type: module description: 'Creates a configurable block showing the local temperature' package: Meetup version: '1.0.0' core: '8.x' modules/custom/temperature/temperature.info.yml
  • 4.
  • 5. 2. Create a simple block2. Create a simple block pluginplugin
  • 6. <?php /** * @file * Contains DrupaltemperaturePluginBlockTemperatureBlock. */ namespace DrupaltemperaturePluginBlock; use DrupalCoreBlockBlockBase; /** * Provides a 'Temperature' block. * * @Block( * id = "temperature", * admin_label = @Translation("Local temperature"), * category = @Translation("Meetup") * ) */ class TemperatureBlock extends BlockBase { public function build() { return [ '#markup' => 'Seems cold outside!', ]; } } modules/custom/temperature/src/Plugin/Block/TemperatureBlock.php
  • 7. use GuzzleHttpClient; class TemperatureBlock extends BlockBase { public function build() { $city = 'Stuttgart, DE' $client = new Client(); $response = $client->get("http://api.openweathermap.org/data/2.5/weather?q=$city"); if ($response->getStatusCode() == '200') { $result = json_decode($response->getBody()); $markup = "Current temperature in<br>$city:<br>"; $markup .= round($result->main->temp - 273.15) . '° C'; } else { $markup = 'Sorry, something went wrong!'; } return [ '#markup' => $markup, ]; } } Adding the "real" content
  • 8.
  • 9. 3. Make block instances3. Make block instances configurableconfigurable
  • 10. block.settings.temperature: type: block_settings label: 'Temperature block' mapping: city: type: string label: 'City for temperature display' modules/custom/temperature/config/schema/temperature.schema.yml
  • 11. use DrupalCoreBlockBlockBase; use DrupalCoreFormFormStateInterface; class TemperatureBlock extends BlockBase { public function build() { $city = $this->configuration['city']; ... } public function buildConfigurationForm(array $form, FormStateInterface $form_state) { $form['city'] = array( '#title' => 'Location', '#type' => 'textfield', '#default_value' => $this->configuration['city'], ); return $form; } public function submitConfigurationForm(array &$form, FormStateInterface $form_state) { $this->configuration['city'] = $form_state->getValue('city'); $this->blockSubmit($form, $form_state); } } modules/custom/temperature/src/Plugin/Block/TemperatureBlock.php
  • 12.
  • 13. 4. Provide a default4. Provide a default configurationconfiguration
  • 14. temperature.settings: type: mapping label: 'Temperature settings' mapping: city: type: string label: 'Default city for temperature display' block.settings.temperature: type: block_settings label: 'Temperature block' mapping: city: type: string label: 'City for temperature display' modules/custom/temperature/config/schema/temperature.schema.yml modules/custom/temperature/config/install/temperature.settings.yml city: 'Stuttgart,DE'
  • 15. ... class TemperatureBlock extends BlockBase { public function defaultConfiguration() { $config = Drupal::config('temperature.settings')->get(); return $config; } public function build() { ... } public function buildConfigurationForm(array $form, FormStateInterface $form_state) { $form['city'] = array( '#title' => 'Location', '#type' => 'textfield', '#default_value' => $this->configuration['city'], ); return $form; } public function submitConfigurationForm(array &$form, FormStateInterface $form_state) { $this->configuration['city'] = $form_state->getValue('city'); $this->blockSubmit($form, $form_state); } } modules/custom/temperature/src/Plugin/Block/TemperatureBlock.php
  • 16.
  • 17. 5. Make default5. Make default configuration editableconfiguration editable
  • 18. temperature.settings: path: '/admin/config/system/temperature' defaults: _form: 'DrupaltemperatureFormSettingsForm' _title: 'Temperature settings' requirements: _permission: 'administer site configuration' modules/custom/temperature/temperature.routing.yml
  • 19. <?php /** * @file * Contains DrupaltemperatureFormSettingsForm */ namespace DrupaltemperatureForm; use DrupalCoreFormConfigFormBase; use DrupalCoreFormFormStateInterface; class SettingsForm extends ConfigFormBase { public function buildForm(array $form, FormStateInterface $form_state) { $form = parent::buildForm($form, $form_state); $form['city'] = [ '#title' => 'Default Location', '#type' => 'textfield', '#default_value' => $this->config('temperature.settings')->get('city'), ]; return $form; } public function submitForm(array &$form, FormStateInterface $form_state) { $this->config('temperature.settings') ->set('city', $form_state->getValue('city')) ->save(); parent::submitForm($form, $form_state); } protected function getEditableConfigNames() { return ['temperature.settings']; } public function getFormId() { return 'temperature_settings'; } } modules/custom/temperature/src/Form/SettingsForm.php
  • 20.