Entities in Drupal 7 & the Entity API #sudrupalcamp April 6, 2013 JD Leonard ModernBizConsulting.com ModernBizConsulting.com ModernBizConsulting.com.

Slides:



Advertisements
Similar presentations
From the eyes of an Administrator A general overview of e-CFunds Administrative Site, including navigation and exploring the features of this powerful.
Advertisements

A brief overview of Drupal 7 By Robin Isard, Systems Librarian Algoma University.
Usage Statistics in Context: related standards and tools Oliver Pesch Chief Strategist, E-Resources EBSCO Information Services Usage Statistics and Publishers:
Dealing with any shopping scenario
Business Development Suit Presented by Thomas Mathews.
Lukas Blunschi Claudio Jossen Donald Kossmann Magdalini Mori Kurt Stockinger.
Accessing and Using the e-Book Collection from EBSCOhost ® When an arrow appears, click to proceed to the next slide at your own pace. To go back, click.
Seattle Drupal Clinic Introduction to Drupal and Web Content Management.
Drupal Online Tutorial A Product of an ENGL 421 class at Purdue University Page 1.
SharePoint 2013 Catalog Sites Brian Culver ● SharePoint Saturday DFW ● March 7, 2015 Build a SharePoint 2013 Search Driven.
Our aims ease the pain – for all our users get with the times better communication with our supporters recruit and engage people to our campaigns raise.
Visual Web Information Extraction With Lixto Robert Baumgartner Sergio Flesca Georg Gottlob.
Drupal Create a website/web app quickly with this Content Management System Jiaying Xu Spring 2011 COMS E6125 Web-enHanced Information.
© 2004, The Trustees of Indiana University 1 OneStart Workflow Basics Brian McGough, Manager, Systems Integration, UITS Ryan Kirkendall, Lead Developer.
Getting an account with WordPress.com Open your web browser ( mozilla firefox, internet explorer, opera, etc.,)
Wordpress Tutorial 22 – 24 April Table of Contents Introduction Designing blog Writing and Publishing blog Pages Posts Categories Tags Links Comments.
The Dr ü G Book: An Intro to Drupal The Dr ü G Book: An Intro to Drupal (Dr ü G: Drupal User ’ s Group - users, not developers) This is an introduction.
Drupal Workshop Introduction to Drupal Part 1: Web Content Management, Advantages/Disadvantages of Drupal, Drupal terminology, Drupal technology, directories.
Walking the walk and talking the talk… T HE L ANGUAGE OF D RUPAL.
Drupal and the CMS Project. Lesson Learned #1 Keep your modules updated, especially when there are security concerns in the update notes 2010 | The Sky’s.
The Drupal 6 menu system: architecture, do, don't and tricks (part 1) Peter Wolanin August 27, 2008 Drupalcon, Szeged.
Dataface API Essentials Steve Hannah Web Lite Solutions Corp.
Lecture 3 – Data Storage with XML+AJAX and MySQL+socket.io
ArcGIS Workflow Manager An Introduction
Administration Tab CiviCRM. Data Organization in CiviCRM: "Building Blocks" Contacts Reports Mail Tags Activities Contribe Member Events and Event Attendences.
® IBM Software Group © 2009 IBM Corporation Rational Publishing Engine RQM Multi Level Report Tutorial David Rennie, IBM Rational Services A/NZ
MSF Requirements Envisioning Phase Planning Phase.
1 The following presentation is from the Oracle Webcast “What’s New in P6 EPPM Release 8.1.” As a partner, you may not use the Oracle Power Point template,
Core Publisher: Creating Programs & Podcasts. Training 1: Site Administration Training 2: Programs Training 3: Content Tagging Training 4: Creating Posts.
Database Publishing Jon Whitener Web Communications Specialist University of Detroit Mercy Jon Whitener Web Communications Specialist University of Detroit.
Tutorial 121 Creating a New Web Forms Page You will find that creating Web Forms is similar to creating traditional Windows applications in Visual Basic.
The Future of Fields or, How Snow and Flu in Chicago Clarified What Drupal is Good For.
Meta Tagging / Metadata Lindsay Berard Assisted by: Li Li.
1 OPOL Training (OrderPro Online) Prepared by Christina Van Metre Independent Educational Consultant CTO, Business Development Team © Training Version.
Drupal Commerce Better than Uber Andrew Root: druroot.
Limits From the initial (HINARI) PubMed page, we will click on the Limits search option. Note also the hyperlinks to Advanced search and Help options.
Nickelodeon – Blogs User Guide. 1. Introduction The admin tool allows you to create and publish blog posts easily and efficiently along with managing.
Chapter 17 Creating a Database.
Drupal Overview Prepared by : Agustin D. Gumogda Jr. Instructor.
Seattle Drupal Clinic Introduction to Drupal Part 1: Web Content Management, Advantages/Disadvantages of Drupal, Drupal terminology.
Introduction to Module Development John Fiala and Ezra Barnett Gildesgame.
Entities in Drupal 7 & the Entity API #sfdug March 11, 2013 JD Leonard ModernBizConsulting.com.
INFO1408 Database Design Concepts Week 15: Introduction to Database Management Systems.
XRX Basic CRUDS Create, Read, Update and Delete and Search XML Data Date: May 2011 Dan McCreary President Dan McCreary & Associates
How does Drupal Work? Information Systems 337 Prof. Harry Plantinga.
Management Information Systems, 4 th Edition 1 Chapter 8 Data and Knowledge Management.
Introduction to Views Stanford Drupal Camp April 6, 2013.
Drupal for client Maria Sherskova skype: sherskova.
Table of Contents TopicSlide Administrator Login 2 Administrator Navigations 3 Managing AlternativeDr.com Blogs 4 Managing Dr. Lloyd May Blogs 5 Managing.
Core Publisher: Creating Programs. Creating Programs in Composer Pro.
 Shopping Basket  Stages to maintain shopping basket in framework  Viewing Shopping Basket.
Forms Manager. What is Forms Manager? Forms Manager is a completely new online form creation and form data management tool.
Retele de senzori Curs 2 - 1st edition UNIVERSITATEA „ TRANSILVANIA ” DIN BRAŞOV FACULTATEA DE INGINERIE ELECTRICĂ ŞI ŞTIINŢA CALCULATOARELOR.
INFM 700 Project 3 (Aqua) - Akashdeep Ray - Arnaud Lawson - Neha AR - Vidisha Vedvyas.
CiviCRM Entity - Superior Drupal Integration A parallel, inclusive vision for the future. A working use case of headless CiviCRM.
Varnish Cache and its usage in the real world Ivan Chepurnyi Owner EcomDev BV.
● The most common website platform ● User friendly-easy to edit ● Constantly improving-updates, plugins, themes Why WordPress?
Khalid Baheyeldin, Toronto, Mar 13, 2007 Building Drupal sites using CCK, Views and Panels Khalid Baheyeldin Drupal Users Group, Toronto.
AEM Digital Asset Management - DAM Author : Nagavardhan
Internet Made Easy! Make sure all your information is always up to date and instantly available to all your clients.
Business Directory REST API
Content Management System
Teaching slides Chapter 8.
One Content Type to Rule Them All
INFO/CSE 100, Spring 2006 Fluency in Information Technology
Advanced Database Concepts: Reports & Views
Best Practices for Designing Effective Map Services: Case Studies
Rational Publishing Engine RQM Multi Level Report Tutorial
SDMX IT Tools SDMX Registry
Presentation transcript:

Entities in Drupal 7 & the Entity API #sudrupalcamp April 6, 2013 JD Leonard ModernBizConsulting.com ModernBizConsulting.com ModernBizConsulting.com Deck is online

About Me Founder & Chief Solutions Modern Biz Consulting in Oakland Strong development background Working with Drupal since 2006 Developer, architect, project manager Focus on complex web application development

Agenda Ways we represent data in D6 vs D7 Entities, entity types, & bundles Fields (formerly CCK) The Entity API contrib module How (and why) to define a custom entity Using EntityFieldQuery Defining entity property info Leveraging the Entity Metadata Wrapper

Poll Who here is... –Brand new to Drupal? –A site builder? –A module developer? –On the business side of things? Who here has... –Created a custom D7 entity? –Not created a custom D7 entity?

D6 Data (Custom database table) User Comment File Taxonomy vocabulary Taxonomy term Node –Page, Blog post, (custom content type)

D7 Data (Custom database table) Entity –User –Comment –File –Taxonomy vocabulary –Taxonomy term –Node Page, Blog post, (custom content type) (Custom entity type)

Entity Types Elemental building block for most important data in Drupal 7 Represents a concept or noun Different types store different data –Generally in a single DB table –Eg: Node Title, body, created timestamp, etc. –Eg: User Username, created timestamp, last visit timestamp, etc. Defined using hook_entity_info()

Entity Instance of an entity type Examples of entities from core: –The user jdleonard with uid –The page “Drupal Rocks” with nid 44 Any entity can be loaded with entity_load() –Eg: entity_load(‘node’, array(44, 65)) Returns an array with two nodes with nids 44 and 65 –Core provides some convenience wrappers Eg: node_load() and user_load()

Entity Bundles Subtype of an entity Eg: Page and Blog post –Two content types (bundles) of node entity type Not all entity types have more than one bundle –Eg: User No subtypes; concept stands on its own

Why We Need Entity Bundles Each entity type stores some data in a table –We call these pieces of data “properties” –Eg: node Title, body, author (uid), created timestamp But not all nodes are created equal –Page may have data beyond that captured by node –Blog posts get tagged –We need fields!

CCK: Content Construction Kit (D6) Contrib module Store additional data per content (node) content type Eg: Fivestar –Contrib module leveraging contrib CCK API –Allows nodes to be rated (think 1-5 stars) –Eg: let users rate pages or blog posts

Fields (D7) Core concept Store additional data per entity type Applies power of CCK to all entity types –Not just nodes! Eg: Fivestar –Contrib module leveraging core Field API –Allows entities to be rated –Eg: let users rate pages, blog posts, users, comments, custom entities

Entities in Core vs Contrib Entities are a Drupal 7 core concept Core provides the “Entity API” –Functions and hooks to define and interact with entities, entity types, and entity bundles Everything we've discussed so far is part of Drupal 7 core (no contrib modules necessary) Not everything “made it into” D7 core –Thankfully there's the “Entity API” contrib module (confusingly named)

Entity API Contrib Module Makes dealing with entities easier Provides full CRUD functionality –CReate, Update, and Delete Allows definition of metadata about entities Optionally makes entity data –Exportable (for configuration) –Revisionable (eg: node revisions) Optional administrative UI for managing entities Object-oriented representation of entity types

Core or contrib Entity API? Documentation for core's Entity API is separate from that for the Entity API contrib module In practice, you'll probably always use the Entity API contrib module –It provides so much awesome functionality! Don't get confused –Always install the Entity API contrib module when defining an entity –Make sure to read the contrib module's documentation

Contrib Modules Defining Entities Commerce –Commerce Product, Commerce Payment Transaction Organic Groups –OG Membership, OG Membership Type Rules –Rules Configuration Message (think activity stream) –Message, Message Type, Message Type Category … and many more!

Example Custom Entity Type TextbookMadness.com –Classified listings for textbooks at schools –Online price comparison shopping (prices from Amazon, Textbooks.com, etc.) Online prices are –Fetched from a third-party API and stored by Drupal –Hereafter known as Offers

How Shall we Define an Offer? We could use the UI to define an offer node with a bunch of fields to store pricing information But there's a lot of overhead! –Don't need/want a page (path) per offer –Don't need/want revisions –Don't need/want node base table information Language (and translation info), Title, Author, Published status, Created date, Commenting, Promoting, etc. – Don't need/want UI for adding, editing, etc. We want an entity!

Implement hook_schema() $schema['tbm_offer'] = array( // SIMPLIFIED FOR SLIDE 'fields' => array( 'offer_id' => array('type' => 'serial'), 'isbn' => array('type' => 'int'), 'retailer_id' => array('type' => 'int'), 'price' => array('type' => 'int'), 'last_updated' => array('type' => 'int'), ), 'primary key' => array('offer_id') );

Implement hook_entity_info() $entities['tbm_offer'] = array( 'label' => t('Offer'), 'plural label' => t('Offers'), 'entity class' => 'Entity', 'controller class' => 'EntityAPIController', 'module' => 'tbm', 'base table' => 'tbm_offer', 'fieldable' => FALSE, 'entity keys' => array( 'id' => 'offer_id', ));

Make an Entity Type Exportable $entities['tbm_offer'] = array( 'label' => t('Offer'), 'plural label' => t('Offers'), 'entity class' => 'Entity', 'controller class' => 'EntityAPIControllerExportable', 'module' => 'tbm', 'base table' => 'tbm_offer', 'fieldable' => FALSE, 'exportable' => TRUE, 'entity keys' => array( 'id' => 'offer_id', 'name' => 'my_machine_name' ));

Make an Entity Type Revisionable $entities['tbm_offer'] = array( 'label' => t('Offer'), 'plural label' => t('Offers'), 'entity class' => 'Entity', 'controller class' => 'EntityAPIController', 'module' => 'tbm', 'base table' => 'tbm_offer', 'revision_table' => 'tbm_o_revision', 'fieldable' => FALSE, 'entity keys' => array( 'id' => 'offer_id', 'revision' => 'revision_id', ));

Other hook_entity_info() configuration $entities['tbm_offer'] = array( … 'entity class' => 'TbmOfferEntity', // Extends Entity class 'controller class' => 'TbmOfferEntityController', 'access callback' => 'tbm_offer_access', 'admin ui' => array( 'path' => 'admin/structure/offers', 'file' => 'tbm.admin.inc', ), 'label callback' => 'entity_class_label', 'uri callback' => 'entity_class_uri', ); // TbmOfferEntity->defaultLabel(), defaultUri()

Entity Property Info hook_entity_property_info() –Defines entity metadata –Provided for core entities Enables all kinds of great functionality in modules that leverage the Entity API contrib module –Examples coming later

Entity Property Info Automatically generated from hook_schema() –Doesn't understand foreign key relationships (references) –Doesn't know when an integer is actually a date (eg: unix timestamps) We can fill in the gaps with hook_entity_property_info_alter()

hook_entity_property_info_alter() $offer = &$info['tbm_offer']['properties']; $offer['url']['type'] = 'uri'; // was a varchar in hook_schema $offer['url']['label'] = 'URL'; $offer['last_updated']['type'] = 'date'; // integer in hook_schema $offer['last_updated']['label'] = t('Last updated'); // Other types: text, token (machine name), integer, decimal, duration, boolean, entity, struct, list

hook_entity_property_info_alter() // Define a new property to reference an offer's retailer (eg: Amazon.com) $offer['retailer'] = array( 'label' => t('Retailer'), 'type' => 'tbm_retailer', // The tbm_retailer entity type 'description' => t('The retailer making the offer.'), 'required' => TRUE, 'schema field' => 'retailer_id', // as defined in hook_schema );

Entity API Integrations Views –Eg: in a view of offers, we can add a retailer relationship and include details about each offer's retailer along with a link to the retailer Rules Search API Features I18n Token system - Eg: [tbm_offer:retailer:created]

EntityFieldQuery Simple and powerful tool for querying entities Helps ensure database portability –Eg: fields might leverage a NoSQL database Can query based on entity properties and field data Can query field data across entity types –Eg: “return all pages and users tagged with taxonomy term 456” Returns entity IDs keyed by entity type –Usually you’ll then load with entity_load()

EntityFieldQuery Example // Published page nodes with an awesome factor < 3.2 (10 per page) $query = new EntityFieldQuery(); $query ->entityCondition('entity_type', 'node') ->entityCondition('bundle', 'page') ->propertyCondition('status', 1) ->fieldCondition('field_awesome_factor', 'value', 3.2, '<') ->fieldOrderBy('field_awesome_factor', 'value', 'DESC') ->pager(10);

EntityFieldQuery Example $result = $query->execute(); // Keyed by entity type if (isset($result['node'])) { $nids = array_keys($result['node']); $pages = node_load_multiple($nids); $same_as_pages = entity_load('node', $nids); }

My Favorite: Entity Metadata Wrappers Wrapper class to make dealing with entity and property values easier You don't always know when a field value exists You don't have to type [LANGUAGE_NONE][0] everywhere Works with either entity ID or fully loaded entity –Eg: $nid and $node both work Uses lazy loading to avoid unneeded database calls –Eg: You can easily save a field value without loading an entire node

Entity Metadata Wrapper Examples // Get node author's address (given $nid) // BEFORE $node = node_load($nid); $author = user_load($node->uid); $ = check_plain($author->mail); // AFTER $wrapper = entity_metadata_wrapper('node', $nid); $ = $wrapper->author->mail->value();

Entity Metadata Wrapper Examples // Set node author's address $wrapper->author->mail = $wrapper->save(); // Iterate over a list of node's taxonomy terms foreach ($wrapper->field_taxonomy_terms->getIterator() as $delta => $term_wrapper) { $label = $term_wrapper->label->value(); }

More Modules! Entity Construction Kit Entity Construction Kit (ECK) Entity Construction Kit Entity Construction Kit –CCK for entities –Create entity types in a UI Entity Cache Entity Cache Entity Cache Entity Cache –Integrates entities with Drupal's Cache API Entity Reference Entity Reference Entity Reference Entity Reference –Like node reference field, but for any type of entity Automatic Entity Label Automatic Entity Label Automatic Entity Label Automatic Entity Label –Generic successor to Automatic Node Titles

More information Entity API documentation Entity API documentation Entity API documentation Entity API documentation –Lots of information in many subpages EntityFieldQuery documentation EntityFieldQuery documentation EntityFieldQuery documentation EntityFieldQuery documentation Entity API contrib module page Entity API contrib module page Entity API contrib module page Entity API contrib module page Stanford Drupal Camp site Stanford Drupal Camp site Deck is on Stanford Drupal Camp siteStanford Drupal Camp site me: jd Follow me: