SlideShare a Scribd company logo
1 of 53
Download to read offline
Playing with form API
Drupal Summer 2017
Register
name
Samuel Solís
nick
@estoyausente
company
Bodeboca
http://www.bodeboca.com
submit
Some background
D6 Form
function form_example_tutorial_6(&$form_state) {
$form['description'] = array(
'#type' => 'item',
'#title' => t('A form with a validation handler'),
);
$form['data'] = array(
'#type' => 'fieldset',
'#title' => t('Data'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['data']['name'] = array(
'#type' => 'textfield',
'#title' => t('First name'),
'#required' => TRUE,
'#default_value' => "First name",
'#description' => "Please enter your first name.",
'#size' => 20,
'#maxlength' => 20,
);
$form['data']['year_of_birth'] = array(
'#type' => 'textfield',
'#title' => "Year of birth",
'#description' => 'Format is "YYYY"',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
D6 Form
function form_example_tutorial_6_ahah(&$form_state) {
$initial_markup = '<div>'
. t('This box will be replaced')
. '</div>';
$form['box'] = array(
'#type' => 'markup',
'#prefix' => '<div id="box">',
'#suffix' => '</div>',
'#value' => $initial_markup,
);
$form['submit'] = array(
'#type' => 'submit',
'#ahah' => array(
'path' => 'examples/ahah_example/simplest_ahah/callback',
'wrapper' => 'box',
),
'#value' => t('Click Me to change box color'),
);
return $form;
}
D7 Form
function form_example_tutorial_7 ($form, &$form_state) {
$form['drupal_summer'] = array(
'#type' => 'radios',
'#options' => array(
'go_to_the_beach' => t('To the beach'),
'go_this_session' => t('To this awesome session'),
'hangover' => t('Sorry, I have a huge hangover'),
),
'#title' => t('Where do you want to go this Saturday Morning?'),
);
$form['learn_something'] = array(
'#type' => 'textfield',
'#title' => t('What do you want to learn?'),
'#states' => array(
'visible' => array(
':input[name="drupal_summer"]' => array('value' => 'go_this_session'),
),
),
);
}
D7 Form
//Exists in D6 too
function _form_example_7_steps() {
return array(
1 => array(
'form' => 'form_example_wizard_7_1',
),
2 => array(
'form' => 'form_example_wizard_7_2',
),
);
}
function form_example_wizard($form, &$form_state) {
if (empty($form_state['step'])) {
$form_state['step'] = 1;
$form_state['step_information'] = _form_example_steps();
}
$step = &$form_state['step'];
drupal_set_title(t('Extensible Wizard: Step @step', array('@step' => $step)));
$form = $form_state['step_information'][$step]['form']($form, $form_state);
if ($step > 1) {
$form['prev'] = array(
'#type' => 'submit',
'#value' => t('Previous'),
'#name' => 'prev',
'#submit' => array('form_example_wizard_previous_submit'),
'#limit_validation_errors' => array(),
);
D7 Form
//Exists in D6 too
function _form_example_element_7_info() {
$types['form_beach'] = array(
'#input' => TRUE ,
'#process' => array('form_beach_process'),
'#element_validate' => array('form_beach_validate'),
'#autocomplete_path' => FALSE,
'#value_callback' => 'form_beach_value',
'#default_value' => array(
'extension' => '',
'location' => '',
'water_temperature' => '',
),
'#theme_wrappers' => array('form_beach_form_element'),
);
return $types;
}
That's all
And what about D8?
Same concept but ...
New types
HTML5 types
"Drupal" types
POO developed
Ajax more powerful
New #types
Special text #types
tel
email
url
search
entity_autocomplete
Number
Range
Weight
Color
Date
Some grouping types
vertical_tabs
dropbutton
operations
details
datelist
...
Defining forms
FormBase
namespace Drupalfapi_exampleForm;
use DrupalCoreFormFormBase;
use DrupalCoreFormFormStateInterface;
class BuildDemo extends FormBase {
public function getFormId() {
return 'fapi_example_simple_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {}
public function validateForm(array &$form, FormStateInterface $form_state) {}
public function submitForm(array &$form, FormStateInterface $form_state) {}
}
ConfigFormBase
namespace DrupalsummerForm;
use DrupalCoreFormConfigFormBase;
use DrupalCoreFormFormStateInterface;
class SummerConfigurationForm extends ConfigFormBase {
public function getFormId() {
return 'your_module_admin_settings';
}
protected function getEditableConfigNames() {
return [
'summer.settings',
];
}
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('summer.settings');
$form['summer_config'] = array(
'#type' => 'textfield',
'#title' => $this->t('Set why this summer is awesome'),
'#default_value' => $config->get('summer_config'),
);
return parent::buildForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
$this->config('summer.settings')
->set('summer_config', $values['summer_config'])
->save();
}
ConfirmFormBase
namespace DrupalbanForm;
use DrupalCoreFormConfirmFormBase;
use DrupalCoreFormFormStateInterface;
class ConfirmParty extends ConfirmFormBase {
public function getFormId() {
return 'confirm_party_form';
}
public function getQuestion() {
return $this->t('Are you sure you want to go to the party this nigth?');
}
public function getConfirmText() {
return $this->t('Yes, give me some beers');
}
public function getCancelUrl() {
return new Url('party.at_home');
}
public function buildForm(array $form, FormStateInterface $form_state) {
return parent::buildForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
//Go to party
}
}
Validating Forms
validateForm()
public function validateForm(array &$form, FormStateInterface $form_state) {
$rings = $form_state->getValue('rings_number');
if ($rings > 1) {
// Set an error for the form element with a key of "rings_number".
$form_state->setErrorByName(
'rings_number',
$this->t('This isn't the One Ring.')
);
}
Validate entities
!=
Validate forms
Entity Form
Alter entity
Validation
Entity
Save entityValidation
Form
Load entity
Submitting Forms /
Processing Form
Data
submitForm()
public function submitForm(array &$form, FormStateInterface $form_state) {
/*
* This would normally be replaced by code that actually does something
* with the value.
*/
$title = $form_state->getValue('title');
drupal_set_message(
$this->t('You specified a title of %title.',
['%title' => $title])
);
}
Integrate the form in
a request
Routing
fapi_example.simple_form:
path: 'examples/fapi-example/simple-form'
defaults:
_form: 'Drupalfapi_exampleFormSimpleForm'
_title: 'Simple Form'
requirements:
_permission: 'access content'
Retrieving a form
outside of routes
Retrieving a form
$extra = '612-123-4567';
$form = Drupal::formBuilder()
->getForm('DrupalmymoduleFormExampleForm', $extra);
...
public function buildForm(array $form, FormStateInterface $form_state, $extra = NULL)
$form['phone_number'] = array(
'#type' => 'tel',
'#title' => $this->t('Your phone number'),
'#value' => $extra,
);
return $form;
}
Altering a form
form_alter
<?php
/**
* Implements hook_form_FORM_ID_alter().
*/
function example2_form_example_form_alter(&$form, DrupalCoreFormFormStateInterface $form_state) {
$form['important_question']['#description'] =
t('Why did not we call the eagles at the beginning of the movie?');
}
States
#states
$form['drink_wine'] = [
'#type' => 'checkbox',
'#title' => 'Do you like wine?',
];
$form['wine_type'] = [
'#type' => 'container',
'#attributes' => [
'class' => 'accommodation',
],
'#states' => [
'invisible' => [
'input[name="drink_wine"]' => ['checked' => FALSE],
],
],
];
$form['wine_type']['type'] = [
'#type' => 'radios',
'#options' => [
'white' => $this->t('White wine'),
'red' => $this->t('Red wine'),
'sparkling ' => $this->t('Sparkling wine'),
],
'#title' => t('Wine type'),
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Submit'),
];
return $form;
#states
Ajax
#ajax
public function buildForm(array $form, FormStateInterface $form_state) {
$form['temperature'] = [
'#title' => $this->t('Temperature'),
'#type' => 'select',
'#options' => $this->getColorTemperatures(),
'#empty_option' => $this->t('- Select a color temperature -'),
'#ajax' => [
// Could also use [get_class($this), 'updateColor'].
'callback' => '::updateColor',
'wrapper' => 'color-wrapper',
],
];
$form['color_wrapper'] = [
'#type' => 'container',
'#attributes' => ['id' => 'color-wrapper'],
];
$temperature = $form_state->getValue('temperature');
if (!empty($temperature)) {
$form['color_wrapper']['color'] = [
'#type' => 'select',
'#title' => $this->t('Color'),
'#options' => $this->getColorsByTemperature($temperature),
];
}
$form['actions'] = [
'#type' => 'actions',
'submit' => [
'#type' => 'submit',
'#value' => $this->t('Submit'),
],
];
return $form;
}
#ajax
public function updateColor(array $form, FormStateInterface $form_state) {
return $form['color_wrapper'];
}
protected function getColorsByTemperature($temperature) {
return $this->getColors()[$temperature]['colors'];
}
protected function getColorTemperatures() {
return array_map(function ($color_data) {
return $color_data['name'];
}, $this->getColors());
}
protected function getColors() {
return [
'warm' => [
'name' => $this->t('Warm'),
'colors' => [
'red' => $this->t('Red'),
'orange' => $this->t('Orange'),
'yellow' => $this->t('Yellow'),
],
],
'cool' => [
'name' => $this->t('Cool'),
'colors' => [
'blue' => $this->t('Blue'),
'purple' => $this->t('Purple'),
'green' => $this->t('Green'),
],
],
];
}
#ajax
Ajax explained
Ajax anatomy
'#ajax' => [
'callback' => 'DrupalmoduleTypeClassName::Ajaxmethod', //path or method
'event' => 'keyup', //The JavaScript event to respond to
'wrapper' => 'aValidId',
'method' => 'replaceWith', //'replaceWith', 'append', 'prepend' ...
'effect' => 'fade',
'progress' => array(
'type' => 'throbber',
'message' => NULL,
),
];
Response
public function Ajaxmethod() {
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand(
'#edit-date-format-suffix',
'<small id="edit-date-format-suffix">' . $format . '</small>'));
return $response;
}
AjaxCommands
OpenDialogCommand
CloseDialogCommand
AjaxResponse
ReplaceCommand
...
https://api.drupal.org/api/drupal/core!core.api.php/group/ajax/8.2.x
Documentation
https://api.drupal.org/api/drupal/elements/8.2.x
https://www.drupal.org/docs/8/api/form-
api/introduction-to-form-api
https://www.drupal.org/docs/8/api/form-
api/configformbase-with-simple-configuration-api
https://www.drupal.org/project/examples
Form API is your
friend!
name
Samuel Solís
nick
@estoyausente
company
Bodeboca
http://www.bodeboca.com

More Related Content

What's hot

Advanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your ViewAdvanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your ViewRyan Cross
 
11. CodeIgniter vederea unei singure inregistrari
11. CodeIgniter vederea unei singure inregistrari11. CodeIgniter vederea unei singure inregistrari
11. CodeIgniter vederea unei singure inregistrariRazvan Raducanu, PhD
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Editionddiers
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoMohamed Mosaad
 
Writing Sensible Code
Writing Sensible CodeWriting Sensible Code
Writing Sensible CodeAnis Ahmad
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Colin O'Dell
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using CodeceptionJeroen van Dijk
 
Datamapper Railskonferenz 2009
Datamapper Railskonferenz 2009Datamapper Railskonferenz 2009
Datamapper Railskonferenz 2009Hussein Morsy
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress sitereferences
 
How else can you write the code in PHP?
How else can you write the code in PHP?How else can you write the code in PHP?
How else can you write the code in PHP?Maksym Hopei
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介Jace Ju
 
ZG PHP - Specification
ZG PHP - SpecificationZG PHP - Specification
ZG PHP - SpecificationRobert Šorn
 
Custom Signals for Uncoupled Design
Custom Signals for Uncoupled DesignCustom Signals for Uncoupled Design
Custom Signals for Uncoupled Designecomsmith
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
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
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConRafael Dohms
 
Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)brockboland
 

What's hot (20)

Advanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your ViewAdvanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your View
 
11. CodeIgniter vederea unei singure inregistrari
11. CodeIgniter vederea unei singure inregistrari11. CodeIgniter vederea unei singure inregistrari
11. CodeIgniter vederea unei singure inregistrari
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
 
Writing Sensible Code
Writing Sensible CodeWriting Sensible Code
Writing Sensible Code
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using Codeception
 
Drupal Form Api
Drupal Form ApiDrupal Form Api
Drupal Form Api
 
Datamapper Railskonferenz 2009
Datamapper Railskonferenz 2009Datamapper Railskonferenz 2009
Datamapper Railskonferenz 2009
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress site
 
How else can you write the code in PHP?
How else can you write the code in PHP?How else can you write the code in PHP?
How else can you write the code in PHP?
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介
 
ZG PHP - Specification
ZG PHP - SpecificationZG PHP - Specification
ZG PHP - Specification
 
Custom Signals for Uncoupled Design
Custom Signals for Uncoupled DesignCustom Signals for Uncoupled Design
Custom Signals for Uncoupled Design
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
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)
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
displaytag
displaytagdisplaytag
displaytag
 
Daily notes
Daily notesDaily notes
Daily notes
 
Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)
 

Similar to Playing with Drupal Form API

Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)Jeff Eaton
 
Михаил Крайнюк - 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
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Formsdrubb
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
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
 
Fields in Core: How to create a custom field
Fields in Core: How to create a custom fieldFields in Core: How to create a custom field
Fields in Core: How to create a custom fieldIvan Zugec
 
R57shell
R57shellR57shell
R57shellady36
 
Symfony CoP: Form component
Symfony CoP: Form componentSymfony CoP: Form component
Symfony CoP: Form componentSamuel ROZE
 
Drupal 9 training ajax
Drupal 9 training ajaxDrupal 9 training ajax
Drupal 9 training ajaxNeelAndrew
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your CodeAbbas Ali
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usagePavel Makhrinsky
 
What's new in the Drupal 7 API?
What's new in the Drupal 7 API?What's new in the Drupal 7 API?
What's new in the Drupal 7 API?Alexandru Badiu
 
Михаил Крайнюк. Form api: ajax-commands
Михаил Крайнюк. Form api: ajax-commandsМихаил Крайнюк. Form api: ajax-commands
Михаил Крайнюк. Form api: ajax-commandsKsenia Rogachenko
 
Михаил Крайнюк. Form api: ajax-commands
Михаил Крайнюк. Form api: ajax-commandsМихаил Крайнюк. Form api: ajax-commands
Михаил Крайнюк. Form api: ajax-commandsDrupalSib
 

Similar to Playing with Drupal Form API (20)

Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
 
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
Михаил Крайнюк - Form API + Drupal 8: Form and AJAXМихаил Крайнюк - Form API + Drupal 8: Form and AJAX
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Forms
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
Framework
FrameworkFramework
Framework
 
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
 
Fields in Core: How to create a custom field
Fields in Core: How to create a custom fieldFields in Core: How to create a custom field
Fields in Core: How to create a custom field
 
R57shell
R57shellR57shell
R57shell
 
8. vederea inregistrarilor
8. vederea inregistrarilor8. vederea inregistrarilor
8. vederea inregistrarilor
 
Symfony CoP: Form component
Symfony CoP: Form componentSymfony CoP: Form component
Symfony CoP: Form component
 
Drupal 9 training ajax
Drupal 9 training ajaxDrupal 9 training ajax
Drupal 9 training ajax
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your Code
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
 
What's new in the Drupal 7 API?
What's new in the Drupal 7 API?What's new in the Drupal 7 API?
What's new in the Drupal 7 API?
 
Михаил Крайнюк. Form api: ajax-commands
Михаил Крайнюк. Form api: ajax-commandsМихаил Крайнюк. Form api: ajax-commands
Михаил Крайнюк. Form api: ajax-commands
 
Михаил Крайнюк. Form api: ajax-commands
Михаил Крайнюк. Form api: ajax-commandsМихаил Крайнюк. Form api: ajax-commands
Михаил Крайнюк. Form api: ajax-commands
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Amp Up Your Admin
Amp Up Your AdminAmp Up Your Admin
Amp Up Your Admin
 
The new form framework
The new form frameworkThe new form framework
The new form framework
 

More from Samuel Solís Fuentes

Hábitos y consejos para sobrevivir a un trabajo sedentario
Hábitos y consejos para sobrevivir a un trabajo sedentarioHábitos y consejos para sobrevivir a un trabajo sedentario
Hábitos y consejos para sobrevivir a un trabajo sedentarioSamuel Solís Fuentes
 
Mejorar tu código mejorando tu comunicación
Mejorar tu código mejorando tu comunicaciónMejorar tu código mejorando tu comunicación
Mejorar tu código mejorando tu comunicaciónSamuel Solís Fuentes
 
Drupal 8 simple page: Mi primer proyecto en Drupal 8.
Drupal 8 simple page: Mi primer proyecto en Drupal 8.Drupal 8 simple page: Mi primer proyecto en Drupal 8.
Drupal 8 simple page: Mi primer proyecto en Drupal 8.Samuel Solís Fuentes
 
Mejorar tu código hablando con el cliente
Mejorar tu código hablando con el clienteMejorar tu código hablando con el cliente
Mejorar tu código hablando con el clienteSamuel Solís Fuentes
 
Taller de introducción al desarrollo de módulos
Taller de introducción al desarrollo de módulosTaller de introducción al desarrollo de módulos
Taller de introducción al desarrollo de módulosSamuel Solís Fuentes
 
Arquitectura de información en drupal
Arquitectura de información en drupalArquitectura de información en drupal
Arquitectura de información en drupalSamuel Solís Fuentes
 

More from Samuel Solís Fuentes (17)

De managers y developers
De managers y developersDe managers y developers
De managers y developers
 
Hábitos y consejos para sobrevivir a un trabajo sedentario
Hábitos y consejos para sobrevivir a un trabajo sedentarioHábitos y consejos para sobrevivir a un trabajo sedentario
Hábitos y consejos para sobrevivir a un trabajo sedentario
 
Drupal intro for Symfony developers
Drupal intro for Symfony developersDrupal intro for Symfony developers
Drupal intro for Symfony developers
 
Querying solr
Querying solrQuerying solr
Querying solr
 
Las tripas de un sistema solr
Las tripas de un sistema solrLas tripas de un sistema solr
Las tripas de un sistema solr
 
Mejorar tu código mejorando tu comunicación
Mejorar tu código mejorando tu comunicaciónMejorar tu código mejorando tu comunicación
Mejorar tu código mejorando tu comunicación
 
Custom entities in d8
Custom entities in d8Custom entities in d8
Custom entities in d8
 
Drupal8 simplepage v2
Drupal8 simplepage v2Drupal8 simplepage v2
Drupal8 simplepage v2
 
Drupal 8 simple page: Mi primer proyecto en Drupal 8.
Drupal 8 simple page: Mi primer proyecto en Drupal 8.Drupal 8 simple page: Mi primer proyecto en Drupal 8.
Drupal 8 simple page: Mi primer proyecto en Drupal 8.
 
Como arreglar este desastre
Como arreglar este desastreComo arreglar este desastre
Como arreglar este desastre
 
Drupal y rails. Nuestra experiencia
Drupal y rails. Nuestra experienciaDrupal y rails. Nuestra experiencia
Drupal y rails. Nuestra experiencia
 
Mejorar tu código hablando con el cliente
Mejorar tu código hablando con el clienteMejorar tu código hablando con el cliente
Mejorar tu código hablando con el cliente
 
Taller de introducción al desarrollo de módulos
Taller de introducción al desarrollo de módulosTaller de introducción al desarrollo de módulos
Taller de introducción al desarrollo de módulos
 
Más limpio que un jaspe.
Más limpio que un jaspe.Más limpio que un jaspe.
Más limpio que un jaspe.
 
Drupal as a framework
Drupal as a frameworkDrupal as a framework
Drupal as a framework
 
Arquitectura de información en drupal
Arquitectura de información en drupalArquitectura de información en drupal
Arquitectura de información en drupal
 
Drupal para desarrolladores
Drupal para desarrolladoresDrupal para desarrolladores
Drupal para desarrolladores
 

Recently uploaded

Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 

Recently uploaded (20)

Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 

Playing with Drupal Form API

  • 1. Playing with form API Drupal Summer 2017
  • 4.
  • 5. D6 Form function form_example_tutorial_6(&$form_state) { $form['description'] = array( '#type' => 'item', '#title' => t('A form with a validation handler'), ); $form['data'] = array( '#type' => 'fieldset', '#title' => t('Data'), '#collapsible' => TRUE, '#collapsed' => FALSE, ); $form['data']['name'] = array( '#type' => 'textfield', '#title' => t('First name'), '#required' => TRUE, '#default_value' => "First name", '#description' => "Please enter your first name.", '#size' => 20, '#maxlength' => 20, ); $form['data']['year_of_birth'] = array( '#type' => 'textfield', '#title' => "Year of birth", '#description' => 'Format is "YYYY"', ); $form['submit'] = array( '#type' => 'submit', '#value' => 'Submit', ); return $form; }
  • 6. D6 Form function form_example_tutorial_6_ahah(&$form_state) { $initial_markup = '<div>' . t('This box will be replaced') . '</div>'; $form['box'] = array( '#type' => 'markup', '#prefix' => '<div id="box">', '#suffix' => '</div>', '#value' => $initial_markup, ); $form['submit'] = array( '#type' => 'submit', '#ahah' => array( 'path' => 'examples/ahah_example/simplest_ahah/callback', 'wrapper' => 'box', ), '#value' => t('Click Me to change box color'), ); return $form; }
  • 7. D7 Form function form_example_tutorial_7 ($form, &$form_state) { $form['drupal_summer'] = array( '#type' => 'radios', '#options' => array( 'go_to_the_beach' => t('To the beach'), 'go_this_session' => t('To this awesome session'), 'hangover' => t('Sorry, I have a huge hangover'), ), '#title' => t('Where do you want to go this Saturday Morning?'), ); $form['learn_something'] = array( '#type' => 'textfield', '#title' => t('What do you want to learn?'), '#states' => array( 'visible' => array( ':input[name="drupal_summer"]' => array('value' => 'go_this_session'), ), ), ); }
  • 8. D7 Form //Exists in D6 too function _form_example_7_steps() { return array( 1 => array( 'form' => 'form_example_wizard_7_1', ), 2 => array( 'form' => 'form_example_wizard_7_2', ), ); } function form_example_wizard($form, &$form_state) { if (empty($form_state['step'])) { $form_state['step'] = 1; $form_state['step_information'] = _form_example_steps(); } $step = &$form_state['step']; drupal_set_title(t('Extensible Wizard: Step @step', array('@step' => $step))); $form = $form_state['step_information'][$step]['form']($form, $form_state); if ($step > 1) { $form['prev'] = array( '#type' => 'submit', '#value' => t('Previous'), '#name' => 'prev', '#submit' => array('form_example_wizard_previous_submit'), '#limit_validation_errors' => array(), );
  • 9. D7 Form //Exists in D6 too function _form_example_element_7_info() { $types['form_beach'] = array( '#input' => TRUE , '#process' => array('form_beach_process'), '#element_validate' => array('form_beach_validate'), '#autocomplete_path' => FALSE, '#value_callback' => 'form_beach_value', '#default_value' => array( 'extension' => '', 'location' => '', 'water_temperature' => '', ), '#theme_wrappers' => array('form_beach_form_element'), ); return $types; }
  • 12.
  • 13. Same concept but ... New types HTML5 types "Drupal" types POO developed Ajax more powerful
  • 17. Range
  • 19. Color
  • 20. Date
  • 23. FormBase namespace Drupalfapi_exampleForm; use DrupalCoreFormFormBase; use DrupalCoreFormFormStateInterface; class BuildDemo extends FormBase { public function getFormId() { return 'fapi_example_simple_form'; } public function buildForm(array $form, FormStateInterface $form_state) {} public function validateForm(array &$form, FormStateInterface $form_state) {} public function submitForm(array &$form, FormStateInterface $form_state) {} }
  • 24. ConfigFormBase namespace DrupalsummerForm; use DrupalCoreFormConfigFormBase; use DrupalCoreFormFormStateInterface; class SummerConfigurationForm extends ConfigFormBase { public function getFormId() { return 'your_module_admin_settings'; } protected function getEditableConfigNames() { return [ 'summer.settings', ]; } public function buildForm(array $form, FormStateInterface $form_state) { $config = $this->config('summer.settings'); $form['summer_config'] = array( '#type' => 'textfield', '#title' => $this->t('Set why this summer is awesome'), '#default_value' => $config->get('summer_config'), ); return parent::buildForm($form, $form_state); } public function submitForm(array &$form, FormStateInterface $form_state) { $values = $form_state->getValues(); $this->config('summer.settings') ->set('summer_config', $values['summer_config']) ->save(); }
  • 25. ConfirmFormBase namespace DrupalbanForm; use DrupalCoreFormConfirmFormBase; use DrupalCoreFormFormStateInterface; class ConfirmParty extends ConfirmFormBase { public function getFormId() { return 'confirm_party_form'; } public function getQuestion() { return $this->t('Are you sure you want to go to the party this nigth?'); } public function getConfirmText() { return $this->t('Yes, give me some beers'); } public function getCancelUrl() { return new Url('party.at_home'); } public function buildForm(array $form, FormStateInterface $form_state) { return parent::buildForm($form, $form_state); } public function submitForm(array &$form, FormStateInterface $form_state) { //Go to party } }
  • 27. validateForm() public function validateForm(array &$form, FormStateInterface $form_state) { $rings = $form_state->getValue('rings_number'); if ($rings > 1) { // Set an error for the form element with a key of "rings_number". $form_state->setErrorByName( 'rings_number', $this->t('This isn't the One Ring.') ); }
  • 29. Entity Form Alter entity Validation Entity Save entityValidation Form Load entity
  • 31. submitForm() public function submitForm(array &$form, FormStateInterface $form_state) { /* * This would normally be replaced by code that actually does something * with the value. */ $title = $form_state->getValue('title'); drupal_set_message( $this->t('You specified a title of %title.', ['%title' => $title]) ); }
  • 32. Integrate the form in a request
  • 35. Retrieving a form $extra = '612-123-4567'; $form = Drupal::formBuilder() ->getForm('DrupalmymoduleFormExampleForm', $extra); ... public function buildForm(array $form, FormStateInterface $form_state, $extra = NULL) $form['phone_number'] = array( '#type' => 'tel', '#title' => $this->t('Your phone number'), '#value' => $extra, ); return $form; }
  • 37.
  • 38. form_alter <?php /** * Implements hook_form_FORM_ID_alter(). */ function example2_form_example_form_alter(&$form, DrupalCoreFormFormStateInterface $form_state) { $form['important_question']['#description'] = t('Why did not we call the eagles at the beginning of the movie?'); }
  • 40. #states $form['drink_wine'] = [ '#type' => 'checkbox', '#title' => 'Do you like wine?', ]; $form['wine_type'] = [ '#type' => 'container', '#attributes' => [ 'class' => 'accommodation', ], '#states' => [ 'invisible' => [ 'input[name="drink_wine"]' => ['checked' => FALSE], ], ], ]; $form['wine_type']['type'] = [ '#type' => 'radios', '#options' => [ 'white' => $this->t('White wine'), 'red' => $this->t('Red wine'), 'sparkling ' => $this->t('Sparkling wine'), ], '#title' => t('Wine type'), ]; $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Submit'), ]; return $form;
  • 42. Ajax
  • 43. #ajax public function buildForm(array $form, FormStateInterface $form_state) { $form['temperature'] = [ '#title' => $this->t('Temperature'), '#type' => 'select', '#options' => $this->getColorTemperatures(), '#empty_option' => $this->t('- Select a color temperature -'), '#ajax' => [ // Could also use [get_class($this), 'updateColor']. 'callback' => '::updateColor', 'wrapper' => 'color-wrapper', ], ]; $form['color_wrapper'] = [ '#type' => 'container', '#attributes' => ['id' => 'color-wrapper'], ]; $temperature = $form_state->getValue('temperature'); if (!empty($temperature)) { $form['color_wrapper']['color'] = [ '#type' => 'select', '#title' => $this->t('Color'), '#options' => $this->getColorsByTemperature($temperature), ]; } $form['actions'] = [ '#type' => 'actions', 'submit' => [ '#type' => 'submit', '#value' => $this->t('Submit'), ], ]; return $form; }
  • 44. #ajax public function updateColor(array $form, FormStateInterface $form_state) { return $form['color_wrapper']; } protected function getColorsByTemperature($temperature) { return $this->getColors()[$temperature]['colors']; } protected function getColorTemperatures() { return array_map(function ($color_data) { return $color_data['name']; }, $this->getColors()); } protected function getColors() { return [ 'warm' => [ 'name' => $this->t('Warm'), 'colors' => [ 'red' => $this->t('Red'), 'orange' => $this->t('Orange'), 'yellow' => $this->t('Yellow'), ], ], 'cool' => [ 'name' => $this->t('Cool'), 'colors' => [ 'blue' => $this->t('Blue'), 'purple' => $this->t('Purple'), 'green' => $this->t('Green'), ], ], ]; }
  • 45. #ajax
  • 47. Ajax anatomy '#ajax' => [ 'callback' => 'DrupalmoduleTypeClassName::Ajaxmethod', //path or method 'event' => 'keyup', //The JavaScript event to respond to 'wrapper' => 'aValidId', 'method' => 'replaceWith', //'replaceWith', 'append', 'prepend' ... 'effect' => 'fade', 'progress' => array( 'type' => 'throbber', 'message' => NULL, ), ];
  • 48. Response public function Ajaxmethod() { $response = new AjaxResponse(); $response->addCommand(new ReplaceCommand( '#edit-date-format-suffix', '<small id="edit-date-format-suffix">' . $format . '</small>')); return $response; }
  • 51.
  • 52. Form API is your friend!