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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

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

Ähnlich wie Introduction to the 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
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...LEDC 2016
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindValentine Matsveiko
 
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
 

Ähnlich wie Introduction to the 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
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
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
 

Kürzlich hochgeladen

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 

Kürzlich hochgeladen (20)

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

Introduction to the 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