SlideShare a Scribd company logo
Drupal 7 development done right:
Leverage entities!
Presented by Wolfgang Ziegler
Who I am...
Wolfgang Ziegler // d.o. fago
wolfgangziegler.net
twitter.com/the_real_fago
Entity API

So this talk is about the

Drupal 7's entity API

and the Entity API module
http://drupal.org/7
http://drupal.org/project/entity
What are entities?

Entities are the foundation for fields, but
Entity != Fieldable Entity

While most entity types are fieldable, not all are.
Drupal's Data
Data
that is integrated into Drupal
Developing with entities

Base your module upon entities (e.g. Search-api)

Store data

Provide new entity types

Extend other entity types

Fields, custom properties
Drupal 7 Entity API
Entities are required to be

Loadable - entity_load()

Identifiable
Drupal 7 – Entity hooks
hook_entity_load(),
hook_entity_presave(),
hook_entity_insert(), hook_entity_update(),
hook_entity_delete(),
hook_entity_prepare_view, hook_entity_view().
Drupal 7: Metadata

Entity-info (bundles, view-modes)

Labels (via entity_label())

URIs (via entity_uri())
EntityFieldQuery

API for querying entities

Conditions on entity properties as well as fields

Query for entity properties and fields (in a single
storage) at once

Query across multiple entity types (only fields).

Extendable via hook_entity_query_alter().
Entity API module

So far, this all is in Drupal 7.

The Entity API module builds upon that to

ease dealing with any entity type

easy providing new entity type
(optionally fieldable, exportable)
Working with entities...

entity_load(), entity_save(), entity_create(), entity_delete()

entity_view(), entity_access(), entity_label(), entity_uri()

entity_id(), entity_extract_ids()

entity_export(), entity_import()

entity_get_info(), entity_get_property_info()
core
Entity property info

A hook defined by the Entity API module.

Allows modules to describe entity properties
(including fields).

Properties have to be described by a set of
defined data types ('text', 'date', 'user', ..)

Includes human readable description, 'getter
callback', optionally a setter, access permissions.
Property info example
// Add meta-data about the basic node properties.
$properties = &$info['node']['properties'];
$properties['title'] = array(
'label' => t("Title"),
'description' => t("The title of the node."),
'setter callback' => 'entity_property_verbatim_set',
'schema field' => 'title',
'required' => TRUE,
);
$properties['author'] = array(
'label' => t("Author"),
'type' => 'user',
'description' => t("The author of the node."),
'getter callback' => 'entity_metadata_node_get_properties',
'setter callback' => 'entity_metadata_node_set_properties',
'setter permission' => 'administer nodes',
'required' => TRUE,
'schema field' => 'uid',
);
Entity metadata wrappers

Some useful wrapper classes that ease dealing
with entities and their properties.
$wrapper = entity_metadata_wrapper('node', $node);
$wrapper = entity_metadata_wrapper('node', $nid);
$wrapper->author->profile->field_name->value();
$wrapper->author->profile->field_name->set('New name');
$wrapper->language('de')->body->summary->value();
$wrapper->author->mail->access('edit') ? TRUE : FALSE;
$wrapper->author->roles->optionsList();
$wrapper->field_files[0]->description = 'The first file';
$wrapper->save();
$node = $wrapper->value();
How to provide a new entity type?

Write your own controller, implement CRUD and
hooks.

Make use of the Entity API module
Using the entity API module....

Implement hook_entity_info().

Define your schema in hook_schema().

Best practice:
{entity_type}_load(),
{entity_type}_create(),
{entity_type}_save(),
{entity_type}_delete_multiple(), ...
EntityAPIController: What it does

It invokes all CRUD related hooks for you!

Document them (template handbooks)→

Invokes field-attachers for you.

Allows using classes...
MyEntity extends Entity

Eases customizing labels, URIs, display or saving.
$entity->entityType();
$entity->identifier();
$entity->view();
$entity->delete();
$entity->save();
$entity->label(), $entity->uri(), $entity->entityInfo(), ..
Fields

Entity-info: Define your entity type as fieldable.

Field attachers are called (including 'view')

Add bundles, optionally exportable:

Add a separate entity type for bundles
Bundle entity (Profile type, Profile)→

Specify the bundle entity type to be 'bundle of'
another entity type (Profile type is bundle of Profile)
Exportable entities

Alternative to ctools exportables

Make use of existing CRUD functionality

Machine-names

Syncs defaults to the database to support hooks
→ provides usual default hook + CRUD hooks
allows using the DB for sorting, filtering, ...→
Make it exportable

Specify your entity type as exportable in
hook_entity_info() + use
EntityAPIControllerExportable

Make use of machine names.
→ specify a 'name' key under entity-keys.

Add entity_exportable_schema_fields() to your
schema ('module', 'status').
Import / Export

$export = entity_export($entity_type, $entity);

$entity = entity_import($entity_type, $export);

By default: Export as JSON
Example profile type in code
/**
* Implements hook_default_profile2_type().
*/
function recruiter_resume_default_profile2_type() {
$items = array();
$items['resume'] = entity_import('profile2_type', '{
"userCategory" : false,
"userView" : false,
"type" : "resume",
"label" : "Resume",
"weight" : "0",
"data" : { "use_page" : 1},
"rdf_mapping" : []
}');
return $items;
}
Module integrations

Very basic entity property info (read-only)

Views integration

Rules integration (events)

Token support for all entity properties via the
“Entity tokens” module

Features integration (for exportables)
Add property info!

Get Views integration (specify schema-field)

Get tokens for all properties, via entity tokens.

Obtain support of modules building upon it like

Rules

Search API

Restful Web Services (short: RestWS)
Entity property info – Best practices

Do not provide the ids of related entities:
Wrong: node:uid & node:author
Right: node:author (data type: user)
→ Entity references having a 'schema-field' get
Views integration.
Admin UI

Enable the admin UI via hook_entity_info().

Provide
an entity form and
an access callback for entity_access().

Customize it by overriding the controller.

UI suits well for managing configuration.
Drupal 7 Entity & Entity API
Entity Form: Best practices

Use form id {entity_type}_form

Put the entity in $form_state[{entity_type}]

Update the entity in $form_state in your submit
handlers and rebuild / finish.

Use entity_form_submit_build_entity() to create
{entity_type}_form_submit_build_{entity_type},
which submit handlers may re-use.
Entity API docs
→ in code entity.api.php
→ in the handbooks
http://drupal.org/node/878784
→ Learn from examples!
Learn from examples...

Profile2:

Fieldable profile entity

Exportable bundle entity (Profile type)

Admin UI implemented via the Entity API UI

Views / Rules / Features integration via Entity API

Test-module, Field-collection, Organic groups,
Rules, Message, Drupal commerce, ....
D7 Development done right?

Work with Drupal's data by building upon entities
and fields.

Manage your data

using new entity types

Fields or entity properties

API: Does it work without forms?
Drupal 8

Classes EntityInterface→

basic CRUD, UUID support built in

See g.d.o./node/171554

CMI API for configuration→
Deprecating configuration entities?
Drupal 8

Entity Property API

hook_entity_property_info()

Close the gap between properties and fields

Translation

Access

Validation
Questions?Questions?
Thanks!

More Related Content

PDF
jQuery secrets
PDF
Drupal 8: Fields reborn
PDF
droidQuery: The Android port of jQuery
PDF
Configuration Entities in Drupal 8
PDF
Your Entity, Your Code
PDF
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
PPTX
Анатолий Поляков - Drupal.ajax framework from a to z
PDF
What's New in Drupal 8: Entity Field API
jQuery secrets
Drupal 8: Fields reborn
droidQuery: The Android port of jQuery
Configuration Entities in Drupal 8
Your Entity, Your Code
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
Анатолий Поляков - Drupal.ajax framework from a to z
What's New in Drupal 8: Entity Field API

What's hot (19)

PPT
Hi5 Opensocial Code Lab Presentation
PDF
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
DOCX
MVest Spring Job Execution
ODP
Pyramid REST
KEY
Grails UI Primer
PDF
Models Best Practices (ZF MVC)
PDF
Functionality Focused Code Organization
PPTX
Symfony2 your way
PPTX
PDF
How I started to love design patterns
PPTX
Rest with Java EE 6 , Security , Backbone.js
PPTX
2. 엔티티 매핑(entity mapping) 2 2 엔티티매핑 2-2-4. 식별자 자동 생성(@generated-value) part2
PDF
Separation of concerns - DPC12
PDF
A resource oriented framework using the DI/AOP/REST triangle
PDF
Ms Ajax Dom Element Class
PDF
Introduction to CQRS and Event Sourcing
KEY
Sexy.js: A Sequential Ajax (Sajax) library for jQuery
PPT
Propel sfugmd
PPTX
Google cloud datastore driver for Google Apps Script DB abstraction
Hi5 Opensocial Code Lab Presentation
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
MVest Spring Job Execution
Pyramid REST
Grails UI Primer
Models Best Practices (ZF MVC)
Functionality Focused Code Organization
Symfony2 your way
How I started to love design patterns
Rest with Java EE 6 , Security , Backbone.js
2. 엔티티 매핑(entity mapping) 2 2 엔티티매핑 2-2-4. 식별자 자동 생성(@generated-value) part2
Separation of concerns - DPC12
A resource oriented framework using the DI/AOP/REST triangle
Ms Ajax Dom Element Class
Introduction to CQRS and Event Sourcing
Sexy.js: A Sequential Ajax (Sajax) library for jQuery
Propel sfugmd
Google cloud datastore driver for Google Apps Script DB abstraction
Ad

Viewers also liked (18)

PPTX
Castanyada 2012
PPT
The Cyber Threat to the Built Estate
PDF
植基於個人本體論的新聞推薦系統
PDF
Kodemint Technologies Pvt Ltd
PPT
Social Engineering, Insider and Cyber Threat
PDF
20130706閃電秀
PPTX
Kodemint brochure
PDF
The IT Cyber Battle
PDF
The Human Threat in Data protection
PPTX
Data Breach and Hacking
PPTX
Employee monitoring updated
PDF
Bootstrap個人網站 20141027
PPTX
Waldrons march 2013 v1.0
PDF
SMEs, Security and How Its a Growing Threat
PPTX
Ernst & Young visuals security survey 2012
PDF
興大資訊社 CPE 訓練宣傳
PDF
Drupalize your data use entities
PDF
寫程式?那些老師沒教的事
Castanyada 2012
The Cyber Threat to the Built Estate
植基於個人本體論的新聞推薦系統
Kodemint Technologies Pvt Ltd
Social Engineering, Insider and Cyber Threat
20130706閃電秀
Kodemint brochure
The IT Cyber Battle
The Human Threat in Data protection
Data Breach and Hacking
Employee monitoring updated
Bootstrap個人網站 20141027
Waldrons march 2013 v1.0
SMEs, Security and How Its a Growing Threat
Ernst & Young visuals security survey 2012
興大資訊社 CPE 訓練宣傳
Drupalize your data use entities
寫程式?那些老師沒教的事
Ad

Similar to Drupal 7 Entity & Entity API (20)

PDF
Entity api
PDF
ознакомления с модулем Entity api
PDF
Understanding the Entity API Module
PDF
Entities in drupal 7
ODP
Создание собственных сущностей с использованием Entity API
PDF
Drupal 8: Entities
ODP
DrupalCafe Kyiv EntityAPI
PPT
Synapse india reviews on drupal 7 entities (stanford)
PDF
Entities, Bundles, and Fields: You need to understand this!
PDF
Entities 101: Understanding Data Structures in Drupal
PDF
Entities in Drupal 8 - Drupal Tech Talk - Bart Feenstra
PPTX
Drupal 7 entities & TextbookMadness.com
PDF
Entity API in Drupal 8 (Drupal Tech Talk October 2014)
PPTX
Build your own entity with Drupal
PDF
Fields, entities, lists, oh my!
PDF
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
PDF
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and Simple
PDF
Your Entity, Your Code
ODP
Drupal 7 field API
ODP
Drupal 8 entities & felds
Entity api
ознакомления с модулем Entity api
Understanding the Entity API Module
Entities in drupal 7
Создание собственных сущностей с использованием Entity API
Drupal 8: Entities
DrupalCafe Kyiv EntityAPI
Synapse india reviews on drupal 7 entities (stanford)
Entities, Bundles, and Fields: You need to understand this!
Entities 101: Understanding Data Structures in Drupal
Entities in Drupal 8 - Drupal Tech Talk - Bart Feenstra
Drupal 7 entities & TextbookMadness.com
Entity API in Drupal 8 (Drupal Tech Talk October 2014)
Build your own entity with Drupal
Fields, entities, lists, oh my!
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and Simple
Your Entity, Your Code
Drupal 7 field API
Drupal 8 entities & felds

More from 均民 戴 (10)

PDF
CKmates - AWS 三大 AI 解決方案:應用影像辨識、聊天機器人與語音轉換以及 Serverless 應用
PDF
CKmates - AWS 雲端運算 基礎服務介紹
PDF
COSCUP 2016 Workshop: 用 Docker 架設班級 git-it 練習環境
PDF
寫程式?那些老師沒教的事 (Git 部分節錄)
PDF
在 DigitalOcean 架設 Gitlab
PDF
Bootstrap個人網站 20141117
PDF
資訊創意課程 - Create A Personal Website 1
PDF
MIS MySQL 入門
PDF
SITCON 2014 - Regular Expression Introduce
PDF
JSON 和 Android 的火花
CKmates - AWS 三大 AI 解決方案:應用影像辨識、聊天機器人與語音轉換以及 Serverless 應用
CKmates - AWS 雲端運算 基礎服務介紹
COSCUP 2016 Workshop: 用 Docker 架設班級 git-it 練習環境
寫程式?那些老師沒教的事 (Git 部分節錄)
在 DigitalOcean 架設 Gitlab
Bootstrap個人網站 20141117
資訊創意課程 - Create A Personal Website 1
MIS MySQL 入門
SITCON 2014 - Regular Expression Introduce
JSON 和 Android 的火花

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Approach and Philosophy of On baking technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Machine learning based COVID-19 study performance prediction
PDF
Empathic Computing: Creating Shared Understanding
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPT
Teaching material agriculture food technology
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
MYSQL Presentation for SQL database connectivity
Advanced methodologies resolving dimensionality complications for autism neur...
Approach and Philosophy of On baking technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Digital-Transformation-Roadmap-for-Companies.pptx
Electronic commerce courselecture one. Pdf
cuic standard and advanced reporting.pdf
Review of recent advances in non-invasive hemoglobin estimation
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
The AUB Centre for AI in Media Proposal.docx
Spectral efficient network and resource selection model in 5G networks
Machine learning based COVID-19 study performance prediction
Empathic Computing: Creating Shared Understanding
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Teaching material agriculture food technology
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Agricultural_Statistics_at_a_Glance_2022_0.pdf

Drupal 7 Entity & Entity API

  • 1. Drupal 7 development done right: Leverage entities! Presented by Wolfgang Ziegler
  • 2. Who I am... Wolfgang Ziegler // d.o. fago wolfgangziegler.net twitter.com/the_real_fago
  • 3. Entity API  So this talk is about the  Drupal 7's entity API  and the Entity API module http://drupal.org/7 http://drupal.org/project/entity
  • 4. What are entities?  Entities are the foundation for fields, but Entity != Fieldable Entity  While most entity types are fieldable, not all are.
  • 7. Developing with entities  Base your module upon entities (e.g. Search-api)  Store data  Provide new entity types  Extend other entity types  Fields, custom properties
  • 8. Drupal 7 Entity API Entities are required to be  Loadable - entity_load()  Identifiable
  • 9. Drupal 7 – Entity hooks hook_entity_load(), hook_entity_presave(), hook_entity_insert(), hook_entity_update(), hook_entity_delete(), hook_entity_prepare_view, hook_entity_view().
  • 10. Drupal 7: Metadata  Entity-info (bundles, view-modes)  Labels (via entity_label())  URIs (via entity_uri())
  • 11. EntityFieldQuery  API for querying entities  Conditions on entity properties as well as fields  Query for entity properties and fields (in a single storage) at once  Query across multiple entity types (only fields).  Extendable via hook_entity_query_alter().
  • 12. Entity API module  So far, this all is in Drupal 7.  The Entity API module builds upon that to  ease dealing with any entity type  easy providing new entity type (optionally fieldable, exportable)
  • 13. Working with entities...  entity_load(), entity_save(), entity_create(), entity_delete()  entity_view(), entity_access(), entity_label(), entity_uri()  entity_id(), entity_extract_ids()  entity_export(), entity_import()  entity_get_info(), entity_get_property_info() core
  • 14. Entity property info  A hook defined by the Entity API module.  Allows modules to describe entity properties (including fields).  Properties have to be described by a set of defined data types ('text', 'date', 'user', ..)  Includes human readable description, 'getter callback', optionally a setter, access permissions.
  • 15. Property info example // Add meta-data about the basic node properties. $properties = &$info['node']['properties']; $properties['title'] = array( 'label' => t("Title"), 'description' => t("The title of the node."), 'setter callback' => 'entity_property_verbatim_set', 'schema field' => 'title', 'required' => TRUE, ); $properties['author'] = array( 'label' => t("Author"), 'type' => 'user', 'description' => t("The author of the node."), 'getter callback' => 'entity_metadata_node_get_properties', 'setter callback' => 'entity_metadata_node_set_properties', 'setter permission' => 'administer nodes', 'required' => TRUE, 'schema field' => 'uid', );
  • 16. Entity metadata wrappers  Some useful wrapper classes that ease dealing with entities and their properties. $wrapper = entity_metadata_wrapper('node', $node); $wrapper = entity_metadata_wrapper('node', $nid); $wrapper->author->profile->field_name->value(); $wrapper->author->profile->field_name->set('New name'); $wrapper->language('de')->body->summary->value(); $wrapper->author->mail->access('edit') ? TRUE : FALSE; $wrapper->author->roles->optionsList(); $wrapper->field_files[0]->description = 'The first file'; $wrapper->save(); $node = $wrapper->value();
  • 17. How to provide a new entity type?  Write your own controller, implement CRUD and hooks.  Make use of the Entity API module
  • 18. Using the entity API module....  Implement hook_entity_info().  Define your schema in hook_schema().  Best practice: {entity_type}_load(), {entity_type}_create(), {entity_type}_save(), {entity_type}_delete_multiple(), ...
  • 19. EntityAPIController: What it does  It invokes all CRUD related hooks for you!  Document them (template handbooks)→  Invokes field-attachers for you.  Allows using classes...
  • 20. MyEntity extends Entity  Eases customizing labels, URIs, display or saving. $entity->entityType(); $entity->identifier(); $entity->view(); $entity->delete(); $entity->save(); $entity->label(), $entity->uri(), $entity->entityInfo(), ..
  • 21. Fields  Entity-info: Define your entity type as fieldable.  Field attachers are called (including 'view')  Add bundles, optionally exportable:  Add a separate entity type for bundles Bundle entity (Profile type, Profile)→  Specify the bundle entity type to be 'bundle of' another entity type (Profile type is bundle of Profile)
  • 22. Exportable entities  Alternative to ctools exportables  Make use of existing CRUD functionality  Machine-names  Syncs defaults to the database to support hooks → provides usual default hook + CRUD hooks allows using the DB for sorting, filtering, ...→
  • 23. Make it exportable  Specify your entity type as exportable in hook_entity_info() + use EntityAPIControllerExportable  Make use of machine names. → specify a 'name' key under entity-keys.  Add entity_exportable_schema_fields() to your schema ('module', 'status').
  • 24. Import / Export  $export = entity_export($entity_type, $entity);  $entity = entity_import($entity_type, $export);  By default: Export as JSON
  • 25. Example profile type in code /** * Implements hook_default_profile2_type(). */ function recruiter_resume_default_profile2_type() { $items = array(); $items['resume'] = entity_import('profile2_type', '{ "userCategory" : false, "userView" : false, "type" : "resume", "label" : "Resume", "weight" : "0", "data" : { "use_page" : 1}, "rdf_mapping" : [] }'); return $items; }
  • 26. Module integrations  Very basic entity property info (read-only)  Views integration  Rules integration (events)  Token support for all entity properties via the “Entity tokens” module  Features integration (for exportables)
  • 27. Add property info!  Get Views integration (specify schema-field)  Get tokens for all properties, via entity tokens.  Obtain support of modules building upon it like  Rules  Search API  Restful Web Services (short: RestWS)
  • 28. Entity property info – Best practices  Do not provide the ids of related entities: Wrong: node:uid & node:author Right: node:author (data type: user) → Entity references having a 'schema-field' get Views integration.
  • 29. Admin UI  Enable the admin UI via hook_entity_info().  Provide an entity form and an access callback for entity_access().  Customize it by overriding the controller.  UI suits well for managing configuration.
  • 31. Entity Form: Best practices  Use form id {entity_type}_form  Put the entity in $form_state[{entity_type}]  Update the entity in $form_state in your submit handlers and rebuild / finish.  Use entity_form_submit_build_entity() to create {entity_type}_form_submit_build_{entity_type}, which submit handlers may re-use.
  • 32. Entity API docs → in code entity.api.php → in the handbooks http://drupal.org/node/878784 → Learn from examples!
  • 33. Learn from examples...  Profile2:  Fieldable profile entity  Exportable bundle entity (Profile type)  Admin UI implemented via the Entity API UI  Views / Rules / Features integration via Entity API  Test-module, Field-collection, Organic groups, Rules, Message, Drupal commerce, ....
  • 34. D7 Development done right?  Work with Drupal's data by building upon entities and fields.  Manage your data  using new entity types  Fields or entity properties  API: Does it work without forms?
  • 35. Drupal 8  Classes EntityInterface→  basic CRUD, UUID support built in  See g.d.o./node/171554  CMI API for configuration→ Deprecating configuration entities?
  • 36. Drupal 8  Entity Property API  hook_entity_property_info()  Close the gap between properties and fields  Translation  Access  Validation