SlideShare une entreprise Scribd logo
1  sur  52
Télécharger pour lire hors ligne
A Gentle Introduction
to the Views API

Dan Muzyka
dan@danmuzyka.com
drupal.org/user/48685
Target Audience
Experience creating views through the UI
Basic working knowledge of PHP
Basic understanding of object-oriented PHP helpful, not
required
No Views development experience
What we will cover
How to act upon and change Views using Views hooks
Building blocks for creating your own custom fields
and filters (and by extrapolation, your own custom
sorts, arguments, etc.)
What we will not cover
How to use the Views UI
How to theme views
Background
Drupal themer and site builder for several years
Module development for about a year
Needed to do highly custom views for a client
Checking Documentation
Better, but without a conceptual
overview I don't understand this.
Much
better!
Goals
Provide conceptual overview
Show where to find documentation
Give tips for searching and deciphering Views code
Illustrate the concepts with examples
Equip you to learn more on your own
Strike a balance between clarity and not insulting your
intelligence
Example Use Case

Zombie Outbreak!
Report of zombies reanimated and destroyed, and
number of brains consumed
Image “Brackishfairy of the DEAD” by Shannon Hayward used under a Creative
Commons Attribution 2.0 License
http://www.flickr.com/photos/sketchink/2314369576/
Modules Used
Views (Duh!)
CTools
Advanced Help
Devel
Field Collection
Date
Drush
Views API Overview
Views Hooks





Procedural programming
Syntax familiar to
module developers and
to themers who use
preprocess functions
Useful for simple
overrides and for
exposing data to Views
classes

Views Classes and Objects



Object-oriented PHP
Useful for creating
custom fields, filters,
sorts, arguments,
relationships, etc.
Good Overview of Views
Hooks and Classes

Chapter 11
Views Hooks
Absolutely, positively essential: hook_views_api()

(This goes in zombies.module)
Views Hooks
Merlinofchaos recommends putting your other hooks in
mymodule.views.inc
Views Hooks
A lot of useful views hooks intercept and change a
view as it's being built
Each of these hooks acts on the view at a particular
stage of the 'Views Lifecycle'
Views Lifecycle Hooks
View Phase

Hook Run Before

Hook Run After

Use

pre_execute()

hook_views_pre_view()

NA

Affect the view early in its lifecycle

build()

hook_views_pre_build()

hook_views_post_build()

Affect the view immediately before or
after it builds the query

execute()

hook_views_pre_execute()

hook_views_post_execute()

Affect the view immediately before or
after the query runs

render()

hook_views_pre_render()
(Themes can also use this
hook)

hook_views_post_render()
Affect the view immediately before or
(Themes can also use this hook) after the HTML markup is generated
Learning about Views
Lifecycle Hooks

Method 1: Contrib Module API Documentation Sites (e.g.
drupalcontrib.org)






Yes, you get SOME information by searching for
hook_views_pre_build, hook_views_pre_execute, etc.
BUT, you get more context by seeing where these hooks
are invoked in the view build process
Search for:


view::pre_execute


view::build


view::execute


view::render
Learning about Views
Lifecycle Hooks
Learning about Views
Lifecycle Hooks

Method 2: Look at where the hooks are invoked in the
view object


You can find the $view->pre_execute(), $view->build(),
$view->execute(), and $view->render() methods in:
views/includes/view.inc
Sample from

views/includes/view.inc
Views hook examples

with Zombies!!!
Views Handlers
Create custom:


Fields



Filters



Sorts



Arguments



Etc.
Adding a Handler


Create the handler file



Make Drupal aware of your handler



Expose your data to your handler



Clear cache!
Adding a Handler
First, an overview of each step
Then, an example with the zombie view
Creating a Handler File
Find an existing handler similar to what you want to
create
Copy the file with the handler definition into your
module directory
Rename the handler file
merlinofchaos recommends this naming convention:
[module]_handler_[type]_[tablename]_[fieldname]
(You don't actually have to be this verbose)
Creating a Handler File


Change the class name in the handler file



Delete the functions you don't want to override



Edit the functions you DO want to override
Making Views Aware
of Your Handler

Drupal 6 method: hook_views_handlers()
Making Views Aware
of Your Handler

Drupal 7 method: Load in your module's .info file
Exposing Data

to Your Handler


hook_views_data()






Use to create new handlers (e.g., a new field you can add
through the Views UI)
Expose data from the database that is not already
exposed to Views

hook_views_data_alter()




Use to force existing fields, filters, etc to load your
handler instead of the existing handler -orChange the data exposed to the existing handler
node_views_data() excerpt
hook_views_data()
Documentation

Excellent resource: advanced_help
help/views/api-tables
hook_views_data_alter()
Easier place to start – just override an existing handler
Figuring out what to override
1. Determine the existing handler: dpm($view) inside one
of the Views lifecycle hooks
2. Determine where in the $data array to put your override:
dpm($data) in hook_views_data_alter() and clear cache
Slightly Contrived Example:
Custom Date of Destruction Field
Class Inheritance
in Field Example

zombies_handler_field_field_data_field_destruction_date
views_handler_field_field
views_handler_field
views_handler
views_object
Handler Method

Documentation

A few commonly-used methods documented in
advanced_help
Drupalcontrib.org: search for
class_name::method_name (e.g.
views_handler_field_field::render_items)
Comments in the code itself
When in doubt, dpm() everything
Less Contrived Example:
Custom Date Filter
Filter Handler Example
Default filter: zombie destruction date >= input date
If the zombie destruction date is NULL (zombie has not
been destroyed, yet), this does not give us result we
want
Filter Handler Example
Add new check box in admin UI:
'Allow content with an empty date field to pass filter'
Class Inheritance
in Filter Example

zombies_handler_filter_field_destruction_date

date_views_filter_handler_simple

views_handler_filter_date

views_handler_filter_numeric

views_handler_filter

views_handler

views_object
Recap
Views Hooks
Make Views aware of your module: hook_views_api()
Act on your view during the view build process: Views
lifecycle hooks
Provide data to your handlers: hook_views_data() and
hook_views_data_alter()
Views Handlers
Provide custom fields, filters, sorts, arguments,
relationships, etc.
Documentation
advanced_help

Comments and code in the
Views module itself
Documentation
Each of these sources has areas of strength and
weakness; if you don't find a helpful answer in one,
try another
General Tips
When in doubt, dpm() everything
grep through the Views directory to find the closest
ancestor class that defines the function you want to
override
Credits
Artwork by Shannon Hayward used under a Creative Commons
Attribution 2.0 license
Brackishfairy of the DEAD:
http://www.flickr.com/photos/sketchink/2314369576/
JASON of the DEAD:
http://www.flickr.com/photos/sketchink/2776234924/
RANDI of the DEAD:
http://www.flickr.com/photos/sketchink/2776238718/
Untitled: http://www.flickr.com/photos/sketchink/5476952538/
Untitled: http://www.flickr.com/photos/sketchink/5476953706/
Credits
Miles, E., Miles, L., Hogbin, E. J., & Stevenson, K. (2011). Drupal's
building blocks: Quickly building web sites with CCK, Views,
and Panels. Upper Saddle River, NJ: Addison-Wesley.
How to Stalk Me
dan@danmuzyka.com
drupal.org/user/48685
groups.drupal.org/user/8040
@danmuzyka
facebook.com/danmuzyka
linkedin.com/in/danmuzyka
IRC: danmuzyka
Questions?

Contenu connexe

Tendances

Writing PHP – The WordPress Way! by Rahul Bansal @WordCamp Mumbai 2017
Writing PHP – The WordPress Way! by Rahul Bansal  @WordCamp Mumbai 2017Writing PHP – The WordPress Way! by Rahul Bansal  @WordCamp Mumbai 2017
Writing PHP – The WordPress Way! by Rahul Bansal @WordCamp Mumbai 2017rtCamp
 
jQuery For Beginners - jQuery Conference 2009
jQuery For Beginners - jQuery Conference 2009jQuery For Beginners - jQuery Conference 2009
jQuery For Beginners - jQuery Conference 2009Ralph Whitbeck
 
워드프레스 플러그인 개발 입문
워드프레스 플러그인 개발 입문워드프레스 플러그인 개발 입문
워드프레스 플러그인 개발 입문Donghyeok Kang
 
An easy guide to Plugin Development
An easy guide to Plugin DevelopmentAn easy guide to Plugin Development
An easy guide to Plugin DevelopmentShinichi Nishikawa
 
Optimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
Optimising Your Front End Workflow With Symfony, Twig, Bower and GulpOptimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
Optimising Your Front End Workflow With Symfony, Twig, Bower and GulpMatthew Davis
 
I use drupal / 我是 OO 師,我用 Drupal
I use drupal / 我是 OO 師,我用 DrupalI use drupal / 我是 OO 師,我用 Drupal
I use drupal / 我是 OO 師,我用 DrupalChris Wu
 
Bridging the gap between designers and developers at the Guardian
Bridging the gap between designers and developers at the GuardianBridging the gap between designers and developers at the Guardian
Bridging the gap between designers and developers at the GuardianKaelig Deloumeau-Prigent
 
Atomic design con pattern lab
Atomic design con pattern labAtomic design con pattern lab
Atomic design con pattern labUX Nights
 

Tendances (8)

Writing PHP – The WordPress Way! by Rahul Bansal @WordCamp Mumbai 2017
Writing PHP – The WordPress Way! by Rahul Bansal  @WordCamp Mumbai 2017Writing PHP – The WordPress Way! by Rahul Bansal  @WordCamp Mumbai 2017
Writing PHP – The WordPress Way! by Rahul Bansal @WordCamp Mumbai 2017
 
jQuery For Beginners - jQuery Conference 2009
jQuery For Beginners - jQuery Conference 2009jQuery For Beginners - jQuery Conference 2009
jQuery For Beginners - jQuery Conference 2009
 
워드프레스 플러그인 개발 입문
워드프레스 플러그인 개발 입문워드프레스 플러그인 개발 입문
워드프레스 플러그인 개발 입문
 
An easy guide to Plugin Development
An easy guide to Plugin DevelopmentAn easy guide to Plugin Development
An easy guide to Plugin Development
 
Optimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
Optimising Your Front End Workflow With Symfony, Twig, Bower and GulpOptimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
Optimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
 
I use drupal / 我是 OO 師,我用 Drupal
I use drupal / 我是 OO 師,我用 DrupalI use drupal / 我是 OO 師,我用 Drupal
I use drupal / 我是 OO 師,我用 Drupal
 
Bridging the gap between designers and developers at the Guardian
Bridging the gap between designers and developers at the GuardianBridging the gap between designers and developers at the Guardian
Bridging the gap between designers and developers at the Guardian
 
Atomic design con pattern lab
Atomic design con pattern labAtomic design con pattern lab
Atomic design con pattern lab
 

Similaire à A Gentle Introduction to Drupal's Views API

Drupal training-by-ruchiwebsolutions
Drupal training-by-ruchiwebsolutionsDrupal training-by-ruchiwebsolutions
Drupal training-by-ruchiwebsolutionsphp2ranjan
 
Drupal Views development
Drupal Views developmentDrupal Views development
Drupal Views developmentOSInet
 
Advanced Web Development
Advanced Web DevelopmentAdvanced Web Development
Advanced Web DevelopmentRobert J. Stein
 
Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8Brian Ward
 
Intro to drupal_7_architecture
Intro to drupal_7_architectureIntro to drupal_7_architecture
Intro to drupal_7_architectureHai Vo Hoang
 
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to DevelopmentWordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to DevelopmentEvan Mullins
 
Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01Tony Frame
 
Drupal Theme Development - DrupalCon Chicago 2011
Drupal Theme Development - DrupalCon Chicago 2011Drupal Theme Development - DrupalCon Chicago 2011
Drupal Theme Development - DrupalCon Chicago 2011Ryan Price
 
12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocratlinoj
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindValentine Matsveiko
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...LEDC 2016
 
Staying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPStaying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPOscar Merida
 
Flcamp2015 - R.E.A.D: Four steps for selecting the right modules
Flcamp2015 - R.E.A.D: Four steps for selecting the right modulesFlcamp2015 - R.E.A.D: Four steps for selecting the right modules
Flcamp2015 - R.E.A.D: Four steps for selecting the right modulesMichael Miles
 
Jay Callicott Drupal Views 2.0 Presentation
Jay Callicott Drupal Views 2.0 PresentationJay Callicott Drupal Views 2.0 Presentation
Jay Callicott Drupal Views 2.0 PresentationMediacurrent
 
Drupal8 corporate training in Hyderabad
Drupal8 corporate training in HyderabadDrupal8 corporate training in Hyderabad
Drupal8 corporate training in Hyderabadphp2ranjan
 
Workshop - The Little Pattern That Could.pdf
Workshop - The Little Pattern That Could.pdfWorkshop - The Little Pattern That Could.pdf
Workshop - The Little Pattern That Could.pdfTobiasGoeschel
 

Similaire à A Gentle Introduction to Drupal's Views API (20)

Dn D Custom 1
Dn D Custom 1Dn D Custom 1
Dn D Custom 1
 
Dn D Custom 1
Dn D Custom 1Dn D Custom 1
Dn D Custom 1
 
Drupal training-by-ruchiwebsolutions
Drupal training-by-ruchiwebsolutionsDrupal training-by-ruchiwebsolutions
Drupal training-by-ruchiwebsolutions
 
Drupal Views development
Drupal Views developmentDrupal Views development
Drupal Views development
 
Advanced Web Development
Advanced Web DevelopmentAdvanced Web Development
Advanced Web Development
 
Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8
 
Intro to drupal_7_architecture
Intro to drupal_7_architectureIntro to drupal_7_architecture
Intro to drupal_7_architecture
 
Drupal @ MediaCamp Athens
Drupal @ MediaCamp Athens Drupal @ MediaCamp Athens
Drupal @ MediaCamp Athens
 
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to DevelopmentWordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
 
Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01
 
Drupal Theme Development - DrupalCon Chicago 2011
Drupal Theme Development - DrupalCon Chicago 2011Drupal Theme Development - DrupalCon Chicago 2011
Drupal Theme Development - DrupalCon Chicago 2011
 
12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
 
Staying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPStaying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHP
 
Flcamp2015 - R.E.A.D: Four steps for selecting the right modules
Flcamp2015 - R.E.A.D: Four steps for selecting the right modulesFlcamp2015 - R.E.A.D: Four steps for selecting the right modules
Flcamp2015 - R.E.A.D: Four steps for selecting the right modules
 
Jay Callicott Drupal Views 2.0 Presentation
Jay Callicott Drupal Views 2.0 PresentationJay Callicott Drupal Views 2.0 Presentation
Jay Callicott Drupal Views 2.0 Presentation
 
Drupal8 corporate training in Hyderabad
Drupal8 corporate training in HyderabadDrupal8 corporate training in Hyderabad
Drupal8 corporate training in Hyderabad
 
What Is Hobo ?
What Is Hobo ?What Is Hobo ?
What Is Hobo ?
 
Workshop - The Little Pattern That Could.pdf
Workshop - The Little Pattern That Could.pdfWorkshop - The Little Pattern That Could.pdf
Workshop - The Little Pattern That Could.pdf
 

Dernier

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 

Dernier (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

A Gentle Introduction to Drupal's Views API

  • 1. A Gentle Introduction to the Views API Dan Muzyka dan@danmuzyka.com drupal.org/user/48685
  • 2. Target Audience Experience creating views through the UI Basic working knowledge of PHP Basic understanding of object-oriented PHP helpful, not required No Views development experience
  • 3. What we will cover How to act upon and change Views using Views hooks Building blocks for creating your own custom fields and filters (and by extrapolation, your own custom sorts, arguments, etc.)
  • 4. What we will not cover How to use the Views UI How to theme views
  • 5. Background Drupal themer and site builder for several years Module development for about a year Needed to do highly custom views for a client
  • 7.
  • 8. Better, but without a conceptual overview I don't understand this.
  • 10. Goals Provide conceptual overview Show where to find documentation Give tips for searching and deciphering Views code Illustrate the concepts with examples Equip you to learn more on your own Strike a balance between clarity and not insulting your intelligence
  • 11. Example Use Case Zombie Outbreak! Report of zombies reanimated and destroyed, and number of brains consumed Image “Brackishfairy of the DEAD” by Shannon Hayward used under a Creative Commons Attribution 2.0 License http://www.flickr.com/photos/sketchink/2314369576/
  • 12. Modules Used Views (Duh!) CTools Advanced Help Devel Field Collection Date Drush
  • 13. Views API Overview Views Hooks    Procedural programming Syntax familiar to module developers and to themers who use preprocess functions Useful for simple overrides and for exposing data to Views classes Views Classes and Objects   Object-oriented PHP Useful for creating custom fields, filters, sorts, arguments, relationships, etc.
  • 14. Good Overview of Views Hooks and Classes Chapter 11
  • 15. Views Hooks Absolutely, positively essential: hook_views_api() (This goes in zombies.module)
  • 16. Views Hooks Merlinofchaos recommends putting your other hooks in mymodule.views.inc
  • 17. Views Hooks A lot of useful views hooks intercept and change a view as it's being built Each of these hooks acts on the view at a particular stage of the 'Views Lifecycle'
  • 18. Views Lifecycle Hooks View Phase Hook Run Before Hook Run After Use pre_execute() hook_views_pre_view() NA Affect the view early in its lifecycle build() hook_views_pre_build() hook_views_post_build() Affect the view immediately before or after it builds the query execute() hook_views_pre_execute() hook_views_post_execute() Affect the view immediately before or after the query runs render() hook_views_pre_render() (Themes can also use this hook) hook_views_post_render() Affect the view immediately before or (Themes can also use this hook) after the HTML markup is generated
  • 19. Learning about Views Lifecycle Hooks Method 1: Contrib Module API Documentation Sites (e.g. drupalcontrib.org)    Yes, you get SOME information by searching for hook_views_pre_build, hook_views_pre_execute, etc. BUT, you get more context by seeing where these hooks are invoked in the view build process Search for:  view::pre_execute  view::build  view::execute  view::render
  • 21. Learning about Views Lifecycle Hooks Method 2: Look at where the hooks are invoked in the view object  You can find the $view->pre_execute(), $view->build(), $view->execute(), and $view->render() methods in: views/includes/view.inc
  • 25. Adding a Handler  Create the handler file  Make Drupal aware of your handler  Expose your data to your handler  Clear cache!
  • 26. Adding a Handler First, an overview of each step Then, an example with the zombie view
  • 27. Creating a Handler File Find an existing handler similar to what you want to create Copy the file with the handler definition into your module directory Rename the handler file merlinofchaos recommends this naming convention: [module]_handler_[type]_[tablename]_[fieldname] (You don't actually have to be this verbose)
  • 28. Creating a Handler File  Change the class name in the handler file  Delete the functions you don't want to override  Edit the functions you DO want to override
  • 29. Making Views Aware of Your Handler Drupal 6 method: hook_views_handlers()
  • 30. Making Views Aware of Your Handler Drupal 7 method: Load in your module's .info file
  • 31. Exposing Data to Your Handler  hook_views_data()    Use to create new handlers (e.g., a new field you can add through the Views UI) Expose data from the database that is not already exposed to Views hook_views_data_alter()   Use to force existing fields, filters, etc to load your handler instead of the existing handler -orChange the data exposed to the existing handler
  • 34. hook_views_data_alter() Easier place to start – just override an existing handler Figuring out what to override 1. Determine the existing handler: dpm($view) inside one of the Views lifecycle hooks 2. Determine where in the $data array to put your override: dpm($data) in hook_views_data_alter() and clear cache
  • 35. Slightly Contrived Example: Custom Date of Destruction Field
  • 36. Class Inheritance in Field Example zombies_handler_field_field_data_field_destruction_date views_handler_field_field views_handler_field views_handler views_object
  • 37. Handler Method Documentation A few commonly-used methods documented in advanced_help Drupalcontrib.org: search for class_name::method_name (e.g. views_handler_field_field::render_items) Comments in the code itself
  • 38. When in doubt, dpm() everything
  • 40. Filter Handler Example Default filter: zombie destruction date >= input date If the zombie destruction date is NULL (zombie has not been destroyed, yet), this does not give us result we want
  • 41. Filter Handler Example Add new check box in admin UI: 'Allow content with an empty date field to pass filter'
  • 42. Class Inheritance in Filter Example zombies_handler_filter_field_destruction_date date_views_filter_handler_simple views_handler_filter_date views_handler_filter_numeric views_handler_filter views_handler views_object
  • 43. Recap
  • 44. Views Hooks Make Views aware of your module: hook_views_api() Act on your view during the view build process: Views lifecycle hooks Provide data to your handlers: hook_views_data() and hook_views_data_alter()
  • 45. Views Handlers Provide custom fields, filters, sorts, arguments, relationships, etc.
  • 46. Documentation advanced_help Comments and code in the Views module itself
  • 47. Documentation Each of these sources has areas of strength and weakness; if you don't find a helpful answer in one, try another
  • 48. General Tips When in doubt, dpm() everything grep through the Views directory to find the closest ancestor class that defines the function you want to override
  • 49. Credits Artwork by Shannon Hayward used under a Creative Commons Attribution 2.0 license Brackishfairy of the DEAD: http://www.flickr.com/photos/sketchink/2314369576/ JASON of the DEAD: http://www.flickr.com/photos/sketchink/2776234924/ RANDI of the DEAD: http://www.flickr.com/photos/sketchink/2776238718/ Untitled: http://www.flickr.com/photos/sketchink/5476952538/ Untitled: http://www.flickr.com/photos/sketchink/5476953706/
  • 50. Credits Miles, E., Miles, L., Hogbin, E. J., & Stevenson, K. (2011). Drupal's building blocks: Quickly building web sites with CCK, Views, and Panels. Upper Saddle River, NJ: Addison-Wesley.
  • 51. How to Stalk Me dan@danmuzyka.com drupal.org/user/48685 groups.drupal.org/user/8040 @danmuzyka facebook.com/danmuzyka linkedin.com/in/danmuzyka IRC: danmuzyka