SlideShare a Scribd company logo
Playing with form API
Drupal Summer 2017
Register
name
Samuel Solís
nick
@estoyausente
company
Bodeboca
http://www.bodeboca.com
submit
Some background
D8 Form api
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?
D8 Form api
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
D8 Form api
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
D8 Form api
Form API is your
friend!
name
Samuel Solís
nick
@estoyausente
company
Bodeboca
http://www.bodeboca.com

More Related Content

KEY
WordCamp Denver 2012 - Custom Meta Boxes
PPT
Drupal Lightning FAPI Jumpstart
PDF
Everything you always wanted to know about forms* *but were afraid to ask
PDF
Leveraging Symfony2 Forms
PPT
Zend framework 04 - forms
PDF
Rapid Prototyping with PEAR
PDF
50 Laravel Tricks in 50 Minutes
PPTX
Quality code by design
WordCamp Denver 2012 - Custom Meta Boxes
Drupal Lightning FAPI Jumpstart
Everything you always wanted to know about forms* *but were afraid to ask
Leveraging Symfony2 Forms
Zend framework 04 - forms
Rapid Prototyping with PEAR
50 Laravel Tricks in 50 Minutes
Quality code by design

What's hot (20)

PPT
Advanced Drupal Views: Theming your View
PPTX
11. CodeIgniter vederea unei singure inregistrari
PDF
Drupal - dbtng 25th Anniversary Edition
PDF
Dig Deeper into WordPress - WD Meetup Cairo
PDF
Writing Sensible Code
PPTX
Hacking Your Way To Better Security - Dutch PHP Conference 2016
PDF
Refactoring using Codeception
PPT
Drupal Form Api
PDF
Datamapper Railskonferenz 2009
PDF
Gail villanueva add muscle to your wordpress site
PDF
How else can you write the code in PHP?
PDF
購物車程式架構簡介
PDF
ZG PHP - Specification
PPTX
Custom Signals for Uncoupled Design
KEY
Symfony2 Building on Alpha / Beta technology
PDF
Code moi une RH! (PHP tour 2017)
PDF
Your code sucks, let's fix it - DPC UnCon
PPT
displaytag
TXT
Daily notes
PDF
Drupal is Stupid (But I Love It Anyway)
Advanced Drupal Views: Theming your View
11. CodeIgniter vederea unei singure inregistrari
Drupal - dbtng 25th Anniversary Edition
Dig Deeper into WordPress - WD Meetup Cairo
Writing Sensible Code
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Refactoring using Codeception
Drupal Form Api
Datamapper Railskonferenz 2009
Gail villanueva add muscle to your wordpress site
How else can you write the code in PHP?
購物車程式架構簡介
ZG PHP - Specification
Custom Signals for Uncoupled Design
Symfony2 Building on Alpha / Beta technology
Code moi une RH! (PHP tour 2017)
Your code sucks, let's fix it - DPC UnCon
displaytag
Daily notes
Drupal is Stupid (But I Love It Anyway)
Ad

Similar to D8 Form api (20)

ZIP
Drupal Development (Part 2)
PDF
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
PDF
Drupal 8: Forms
PDF
laravel tricks in 50minutes
PPT
Framework
PDF
Mikhail Kraynuk. Form api. Drupal 8
PDF
Mikhail Kraynuk. Form api. Drupal 8
KEY
Fields in Core: How to create a custom field
PDF
R57shell
PPTX
8. vederea inregistrarilor
PDF
Symfony CoP: Form component
PPTX
Drupal 9 training ajax
PPTX
Tidy Up Your Code
PDF
Drupal Field API. Practical usage
ZIP
What's new in the Drupal 7 API?
PDF
Михаил Крайнюк. Form api: ajax-commands
PDF
Михаил Крайнюк. Form api: ajax-commands
KEY
Unit testing zend framework apps
PPTX
Amp Up Your Admin
PDF
The new form framework
Drupal Development (Part 2)
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
Drupal 8: Forms
laravel tricks in 50minutes
Framework
Mikhail Kraynuk. Form api. Drupal 8
Mikhail Kraynuk. Form api. Drupal 8
Fields in Core: How to create a custom field
R57shell
8. vederea inregistrarilor
Symfony CoP: Form component
Drupal 9 training ajax
Tidy Up Your Code
Drupal Field API. Practical usage
What's new in the Drupal 7 API?
Михаил Крайнюк. Form api: ajax-commands
Михаил Крайнюк. Form api: ajax-commands
Unit testing zend framework apps
Amp Up Your Admin
The new form framework
Ad

More from Samuel Solís Fuentes (19)

PDF
Beyond coding. How management experience made me a better developer
PDF
El necesario mal del Legacy Code (Drupal Iberia 2024)
PDF
De managers y developers
PDF
Hábitos y consejos para sobrevivir a un trabajo sedentario
PDF
Drupal intro for Symfony developers
PDF
Querying solr
PDF
Las tripas de un sistema solr
PDF
Mejorar tu código mejorando tu comunicación
PDF
Custom entities in d8
PDF
Drupal8 simplepage v2
PDF
Drupal 8 simple page: Mi primer proyecto en Drupal 8.
PDF
Como arreglar este desastre
PDF
Drupal y rails. Nuestra experiencia
PDF
Mejorar tu código hablando con el cliente
PDF
Taller de introducción al desarrollo de módulos
PDF
Más limpio que un jaspe.
PDF
Drupal as a framework
PDF
Arquitectura de información en drupal
PDF
Drupal para desarrolladores
Beyond coding. How management experience made me a better developer
El necesario mal del Legacy Code (Drupal Iberia 2024)
De managers y developers
Hábitos y consejos para sobrevivir a un trabajo sedentario
Drupal intro for Symfony developers
Querying solr
Las tripas de un sistema solr
Mejorar tu código mejorando tu comunicación
Custom entities in d8
Drupal8 simplepage v2
Drupal 8 simple page: Mi primer proyecto en Drupal 8.
Como arreglar este desastre
Drupal y rails. Nuestra experiencia
Mejorar tu código hablando con el cliente
Taller de introducción al desarrollo de módulos
Más limpio que un jaspe.
Drupal as a framework
Arquitectura de información en drupal
Drupal para desarrolladores

Recently uploaded (20)

PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Transform Your Business with a Software ERP System
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Digital Systems & Binary Numbers (comprehensive )
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
history of c programming in notes for students .pptx
PPTX
Introduction to Artificial Intelligence
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
Computer Software and OS of computer science of grade 11.pptx
PPT
Introduction Database Management System for Course Database
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
ai tools demonstartion for schools and inter college
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Transform Your Business with a Software ERP System
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Digital Systems & Binary Numbers (comprehensive )
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Understanding Forklifts - TECH EHS Solution
Softaken Excel to vCard Converter Software.pdf
Reimagine Home Health with the Power of Agentic AI​
history of c programming in notes for students .pptx
Introduction to Artificial Intelligence
VVF-Customer-Presentation2025-Ver1.9.pptx
Computer Software and OS of computer science of grade 11.pptx
Introduction Database Management System for Course Database
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Adobe Illustrator 28.6 Crack My Vision of Vector Design
ai tools demonstartion for schools and inter college
How to Choose the Right IT Partner for Your Business in Malaysia

D8 Form api