SlideShare a Scribd company logo
1 of 37
Download to read offline
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.
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

What's hot

Hi5 Opensocial Code Lab Presentation
Hi5 Opensocial Code Lab PresentationHi5 Opensocial Code Lab Presentation
Hi5 Opensocial Code Lab Presentationplindner
 
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...allilevine
 
MVest Spring Job Execution
MVest Spring Job ExecutionMVest Spring Job Execution
MVest Spring Job ExecutionShraddha Bora
 
Models Best Practices (ZF MVC)
Models Best Practices (ZF MVC)Models Best Practices (ZF MVC)
Models Best Practices (ZF MVC)eddiejaoude
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code OrganizationRebecca Murphey
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patternsSamuel ROZE
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
A resource oriented framework using the DI/AOP/REST triangle
A resource oriented framework using the DI/AOP/REST triangleA resource oriented framework using the DI/AOP/REST triangle
A resource oriented framework using the DI/AOP/REST triangleAkihito Koriyama
 
Introduction to CQRS and Event Sourcing
Introduction to CQRS and Event SourcingIntroduction to CQRS and Event Sourcing
Introduction to CQRS and Event SourcingSamuel ROZE
 
Sexy.js: A Sequential Ajax (Sajax) library for jQuery
Sexy.js: A Sequential Ajax (Sajax) library for jQuerySexy.js: A Sequential Ajax (Sajax) library for jQuery
Sexy.js: A Sequential Ajax (Sajax) library for jQueryDave Furfero
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmdiKlaus
 
Google cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstractionGoogle cloud datastore driver for Google Apps Script DB abstraction
Google cloud datastore driver for Google Apps Script DB abstractionBruce McPherson
 

What's hot (19)

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

Viewers also liked

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

Viewers also liked (18)

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

Similar to Drupal 7 Entity & Entity API

Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7Zsolt Tasnadi
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comJD Leonard
 
Understanding the Entity API Module
Understanding the Entity API ModuleUnderstanding the Entity API Module
Understanding the Entity API ModuleSergiu Savva
 
Synapse india reviews on drupal 7 entities (stanford)
Synapse india reviews on drupal 7 entities (stanford)Synapse india reviews on drupal 7 entities (stanford)
Synapse india reviews on drupal 7 entities (stanford)Tarunsingh198
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your CodeDrupalDay
 
Drupal 8 entities & felds
Drupal 8 entities & feldsDrupal 8 entities & felds
Drupal 8 entities & feldsAndy Postnikov
 
Drupal 8: Entities
Drupal 8: EntitiesDrupal 8: Entities
Drupal 8: Entitiesdrubb
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rulesSrijan Technologies
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...SPTechCon
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreIMC Institute
 
First Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven DevelopmentFirst Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven DevelopmentNuvole
 
Perl: Hate it for the Right Reasons
Perl: Hate it for the Right ReasonsPerl: Hate it for the Right Reasons
Perl: Hate it for the Right ReasonsMatt Follett
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto UniversitySC5.io
 

Similar to Drupal 7 Entity & Entity API (20)

Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
 
Entity api
Entity apiEntity api
Entity api
 
Understanding the Entity API Module
Understanding the Entity API ModuleUnderstanding the Entity API Module
Understanding the Entity API Module
 
Synapse india reviews on drupal 7 entities (stanford)
Synapse india reviews on drupal 7 entities (stanford)Synapse india reviews on drupal 7 entities (stanford)
Synapse india reviews on drupal 7 entities (stanford)
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Drupal 8 Hooks
Drupal 8 HooksDrupal 8 Hooks
Drupal 8 Hooks
 
Drupal 8 entities & felds
Drupal 8 entities & feldsDrupal 8 entities & felds
Drupal 8 entities & felds
 
Drupal 8: Entities
Drupal 8: EntitiesDrupal 8: Entities
Drupal 8: Entities
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
 
Drupal 7 field API
Drupal 7 field APIDrupal 7 field API
Drupal 7 field API
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
 
Field api.From d7 to d8
Field api.From d7 to d8Field api.From d7 to d8
Field api.From d7 to d8
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
 
First Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven DevelopmentFirst Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven Development
 
Perl: Hate it for the Right Reasons
Perl: Hate it for the Right ReasonsPerl: Hate it for the Right Reasons
Perl: Hate it for the Right Reasons
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
 

More from 均民 戴

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

More from 均民 戴 (10)

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

Recently uploaded

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
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
 
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
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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...
 
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
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

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.
  • 30.
  • 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