SlideShare uma empresa Scribd logo
1 de 28
Entity API
Understanding the Entity API Module
Sergiu Savva
Drupal developerwearepropeople.com
Summary
1. An introduction to entities
2. Entity types
3. Bundles
4. Fields
5. Entity
6. Entity API
7. Entity metadata wrapper
8. Getters ,Setters, Multilingual
An Introduction to Entities
We can build Entity types, which can make
Bundles, to which we can add Fields and then
create Entities.
Entity types > Bundles > Fields > Entities
Entity types
Fieldable entities make Drupal eminently
flexible. An entity type is a useful abstraction
to group together fields.
● Flexible
● Fieldable
● Used by Views and Rules
Entity types
● Nodes (content)
● User profiles
● Taxonomy terms
● Comments
Some examples of entity types:
Entity types
● label - The human-readable name of the type.
● controller class - The name of the class that is used to load the
objects.
● fieldable - Set to TRUE if you want your entity type to accept fields
being attached to it.
● bundles - An array describing all bundles for this object type.
● view modes - An array describing the view modes for the entity
type.
You can also build new kinds of entity types if the
options above don't suit your needs.
Read further about using the hook_entity_info()
Bundles
Bundles are an implementation of an entity type
to which fields can be attached. You can consider
bundles as subtypes of an entity type.
Bundles for entity type node:
Fields
Fields can be added to any of the bundles or
entity types to help organize their data.
Entity
An entity would be one instance of a particular
entity type such as a comment, taxonomy term,
user profile or a bundle such as a blog post, article
or product.
● An entity type is a base class
● A bundle is an extended class
● A field is a class member, property, variable or field instance
(depending on your naming preference)
● An entity is an object or instance of a base or extended class
Relation Entity - Field
Entity Fields
title
body
taxonomy
some text
number
Bundles
Node Page
News title
body
taxonomy
some text
number
Entity
Entity functions from core:
entity_get_controller Get the entity controller class for an entity type.
entity_get_info Get the entity info array of an entity type.
entity_label Returns the label of an entity.
entity_language Returns the language of an entity.
entity_load Load entities from the database.
entity_load_unchanged Loads the unchanged, i.e. not modified, entity from the database.
entity_prepare_view Invoke hook_entity_prepare_view().
entity_uri Returns the URI elements of an entity.
Core entities
entity_get_info($entity_type = NULL)
File : common.inc
Get the entity info array of an entity type.
Entity vs. Entity API
Entity API (contrib)
The project Entity API extends the entity API of Drupal
core in order to provide an unified way to deal with
entities and their properties.
Additionally, it provides an entity CRUD* controller, which
helps with simplifying the creation of new entity types.
[ CRUD - Create, read, update and delete ]
Entity API (contrib)
Name Description
entity_access Determines whether the given user has access to an entity.
entity_create Create a new entity object.
entity_delete Permanently delete the given entity.
entity_delete_multiple Permanently delete multiple entities.
entity_export Exports an entity.
ntity_import Imports an entity.
entity_load_single A wrapper around entity_load() to load a single entity by name or numeric id.
entity_metadata_wrapper Returns a property wrapper for the given data.
entity_revision_delete Deletes an entity revision.
entity_revision_load Loads an entity revision.
entity_save Permanently save an entity.
entity_theme Implements hook_theme().
entity_type_is_fieldable Checks whether an entity type is fieldable.
entity_view Generate an array for rendering the given entities.
entity_get_property_info Get the entity property info array of an entity type.
Entity API hooks
● hook_entity_view
● hook_entity_insert
● hook_entity_update
● hook_entity_presave
● hook_entity_delete
● hook_entity_load
Entity metadata wrapper
Why use entity metadata wrappers?
● Makes your code more readable
● Provides a standardised way of accessing field values and entities
through an API
● Stops you hard coding the language key into the array lookups
● Stops those nasty PHP warnings when you are trying to access
properties that do not exist
● The wrapper autoloads entities (when used in conjunction with
the ->value() accessor), which allow you to chain the callbacks
Entity metadata wrapper
$wrapper = entity_metadata_wrapper('node', $nid);
$mail = $wrapper-->author->mail-->value();
$wrapper-->author-->mail-->set('fago@example.com');
$text = $wrapper-->field_text-->value();
$wrapper-->language('de')-->field_text-->value();
$terms = $wrapper-->field_tags-->value();
$wrapper-->field_tags[] = $term;
$options = $wrapper-->field_tags-->optionsList();
$label = $wrapper-->field_tags[0]-->label();
$access = $wrapper-->field_tags-->access('edit');
Entity metadata wrapper
$node = entity_load_single('node',1);
$entity_wrapper = entity_metadata_wrapper('node', $node);
$entity_wrapper = entity_metadata_wrapper('node', 1);
Load
OR
Entity metadata wrapper
Getters
$entity_wrapper = entity_metadata_wrapper('node', 1);
dpm($entity_wrapper->field_product->raw());
dpm($entity_wrapper->field_product->value());
Entity metadata wrapper
Getters
$entity_wrapper = entity_metadata_wrapper('node', 1);
dpm($entity_wrapper->value());
Entity metadata wrapper
$wrapper = entity_metadata_wrapper('node', 1);
$mail = $wrapper->author->mail->value();
$wrapper->author->mail->set('foo@mail.com');
$wrapper->author->mail = 'foo@mail.com';
$wrapper->author->save();
Setters
Entity metadata wrapper
Multilingual
$wrapper = entity_metadata_wrapper('node',1);
dpm($wrapper->title_field->value());
dpm($wrapper->language('ro')->title_field->value());
dpm($wrapper->language('ru')->title_field->value());
Entity metadata wrapper in life
// add the items from the 'show_features' taxonomy
$show_features = array();
$features = $series->field_features;
if (is_array($features[LANGUAGE_NONE])) {
foreach($features[LANGUAGE_NONE] as $tids) {
$tid = $tids['tid'];
$term = taxonomy_term_load($tid);
$featureList[] = $term->name;
}
}
Old approach
Entity metadata wrapper in life
// add the items from the 'show_features' taxonomy
$show_features = array();
foreach ($wrapper->field_features->value() => $feature) {
$show_features[] = $feature->name;
}
Entity metadata wrapper approach
Questions ?
Thank you!

Mais conteúdo relacionado

Mais procurados

Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
backdoor
 

Mais procurados (20)

Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Iterator
IteratorIterator
Iterator
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
Reflection in C#
Reflection in C#Reflection in C#
Reflection in C#
 
.NET Reflection
.NET Reflection.NET Reflection
.NET Reflection
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Java core - Detailed Overview
Java  core - Detailed OverviewJava  core - Detailed Overview
Java core - Detailed Overview
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 
Lecture 24
Lecture 24Lecture 24
Lecture 24
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classes
 
Oops
OopsOops
Oops
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Reflection power pointpresentation ppt
Reflection power pointpresentation pptReflection power pointpresentation ppt
Reflection power pointpresentation ppt
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Reflecting On The Code Dom
Reflecting On The Code DomReflecting On The Code Dom
Reflecting On The Code Dom
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Wrapper class (130240116056)
Wrapper class (130240116056)Wrapper class (130240116056)
Wrapper class (130240116056)
 
Smoke and Mirrors - Reflection in C#
Smoke and Mirrors - Reflection in C#Smoke and Mirrors - Reflection in C#
Smoke and Mirrors - Reflection in C#
 

Destaque

Windows 7- System Zariadenia a tlačiareň
Windows 7- System Zariadenia a tlačiareň Windows 7- System Zariadenia a tlačiareň
Windows 7- System Zariadenia a tlačiareň
gymmoldava
 
áLbum de fotografías
áLbum de fotografíasáLbum de fotografías
áLbum de fotografías
Sandy_v
 

Destaque (20)

12 formas basicas de enseñar
12 formas basicas de enseñar12 formas basicas de enseñar
12 formas basicas de enseñar
 
Windows 7- System Zariadenia a tlačiareň
Windows 7- System Zariadenia a tlačiareň Windows 7- System Zariadenia a tlačiareň
Windows 7- System Zariadenia a tlačiareň
 
La madre
La madreLa madre
La madre
 
Literacia financeiras 6ºd
Literacia financeiras   6ºdLiteracia financeiras   6ºd
Literacia financeiras 6ºd
 
Logico matematico
Logico matematicoLogico matematico
Logico matematico
 
Что окружает нас дома
Что окружает нас домаЧто окружает нас дома
Что окружает нас дома
 
PM C project_certificate
PM C project_certificatePM C project_certificate
PM C project_certificate
 
На что похожа наша планета
На что похожа наша планетаНа что похожа наша планета
На что похожа наша планета
 
Aebli preguntas
Aebli preguntasAebli preguntas
Aebli preguntas
 
Activadad 2 1_jessica_giler_tecnologia
Activadad 2 1_jessica_giler_tecnologiaActivadad 2 1_jessica_giler_tecnologia
Activadad 2 1_jessica_giler_tecnologia
 
áLbum de fotografías
áLbum de fotografíasáLbum de fotografías
áLbum de fotografías
 
Patrón de diapositivas
Patrón de diapositivasPatrón de diapositivas
Patrón de diapositivas
 
Deportes
DeportesDeportes
Deportes
 
A prevenção e a precaução na gestão empresarial e pública
A prevenção e a precaução na gestão empresarial e públicaA prevenção e a precaução na gestão empresarial e pública
A prevenção e a precaução na gestão empresarial e pública
 
Facet api
Facet apiFacet api
Facet api
 
Test slideshare
Test slideshareTest slideshare
Test slideshare
 
Módulo2
Módulo2Módulo2
Módulo2
 
Calendario exposiciones perinvestigativo
Calendario exposiciones perinvestigativoCalendario exposiciones perinvestigativo
Calendario exposiciones perinvestigativo
 
Periodismo de Ecuador desafíos
Periodismo de Ecuador desafíosPeriodismo de Ecuador desafíos
Periodismo de Ecuador desafíos
 
12 formas basicas para enseñar
12 formas basicas para enseñar 12 formas basicas para enseñar
12 formas basicas para enseñar
 

Semelhante a ознакомления с модулем Entity api

Working with oro crm entities
Working with oro crm entitiesWorking with oro crm entities
Working with oro crm entities
Oro Inc.
 
Entities, Bundles, and Fields: You need to understand this!
Entities, Bundles, and Fields: You need to understand this!Entities, Bundles, and Fields: You need to understand this!
Entities, Bundles, and Fields: You need to understand this!
tedbow
 
Hibernate Training Session1
Hibernate Training Session1Hibernate Training Session1
Hibernate Training Session1
Asad Khan
 
Databases and doctrine
Databases and doctrineDatabases and doctrine
Databases and doctrine
Glenn Guden
 
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Ranel Padon
 
ActionScript 3.0 Fundamentals
ActionScript 3.0 FundamentalsActionScript 3.0 Fundamentals
ActionScript 3.0 Fundamentals
Saurabh Narula
 

Semelhante a ознакомления с модулем Entity api (20)

Working with oro crm entities
Working with oro crm entitiesWorking with oro crm entities
Working with oro crm entities
 
Entities, Bundles, and Fields: You need to understand this!
Entities, Bundles, and Fields: You need to understand this!Entities, Bundles, and Fields: You need to understand this!
Entities, Bundles, and Fields: You need to understand this!
 
.NET Core, ASP.NET Core Course, Session 13
.NET Core, ASP.NET Core Course, Session 13.NET Core, ASP.NET Core Course, Session 13
.NET Core, ASP.NET Core Course, Session 13
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
 
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)
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
 
Drupal 7 Entity & Entity API
Drupal 7 Entity & Entity APIDrupal 7 Entity & Entity API
Drupal 7 Entity & Entity API
 
Drupal 7 field API
Drupal 7 field APIDrupal 7 field API
Drupal 7 field API
 
Linq
LinqLinq
Linq
 
Entity api
Entity apiEntity api
Entity api
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
 
Hibernate Training Session1
Hibernate Training Session1Hibernate Training Session1
Hibernate Training Session1
 
(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP(An Extended) Beginners Guide to Object Orientation in PHP
(An Extended) Beginners Guide to Object Orientation in PHP
 
Databases and doctrine
Databases and doctrineDatabases and doctrine
Databases and doctrine
 
Chapter 1 Presentation
Chapter 1 PresentationChapter 1 Presentation
Chapter 1 Presentation
 
Entity Framework 4
Entity Framework 4Entity Framework 4
Entity Framework 4
 
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
Batch Scripting with Drupal (Featuring the EntityFieldQuery API)
 
ActionScript 3.0 Fundamentals
ActionScript 3.0 FundamentalsActionScript 3.0 Fundamentals
ActionScript 3.0 Fundamentals
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301
 

Mais de DrupalCamp Kyiv Рысь

система управления конфигурацией в Drupal 8. анализ результатов изменений.
система управления конфигурацией в Drupal 8. анализ результатов изменений.система управления конфигурацией в Drupal 8. анализ результатов изменений.
система управления конфигурацией в Drupal 8. анализ результатов изменений.
DrupalCamp Kyiv Рысь
 
Drupal 7 и history.js или как ajax инфицировать сайт
Drupal 7 и history.js или как ajax инфицировать сайтDrupal 7 и history.js или как ajax инфицировать сайт
Drupal 7 и history.js или как ajax инфицировать сайт
DrupalCamp Kyiv Рысь
 
Cdn hosting решения для drupal (medium)
Cdn hosting   решения для drupal (medium)Cdn hosting   решения для drupal (medium)
Cdn hosting решения для drupal (medium)
DrupalCamp Kyiv Рысь
 
Aegir. развертывание и управление большой сетью drupal сайтов
Aegir. развертывание и управление большой сетью drupal сайтовAegir. развертывание и управление большой сетью drupal сайтов
Aegir. развертывание и управление большой сетью drupal сайтов
DrupalCamp Kyiv Рысь
 

Mais de DrupalCamp Kyiv Рысь (16)

Drupal association slides us 2013
Drupal association slides us 2013Drupal association slides us 2013
Drupal association slides us 2013
 
Drupal association slides ru
Drupal association slides ruDrupal association slides ru
Drupal association slides ru
 
#D8 cx: upgrade your modules to drupal 8
#D8 cx: upgrade your modules to drupal 8 #D8 cx: upgrade your modules to drupal 8
#D8 cx: upgrade your modules to drupal 8
 
Game of-sales-presentation
Game of-sales-presentationGame of-sales-presentation
Game of-sales-presentation
 
Backbone js-slides
Backbone js-slidesBackbone js-slides
Backbone js-slides
 
система управления конфигурацией в Drupal 8. анализ результатов изменений.
система управления конфигурацией в Drupal 8. анализ результатов изменений.система управления конфигурацией в Drupal 8. анализ результатов изменений.
система управления конфигурацией в Drupal 8. анализ результатов изменений.
 
симфони это не страшно
симфони   это не страшносимфони   это не страшно
симфони это не страшно
 
Services в drupal 8
Services в drupal 8Services в drupal 8
Services в drupal 8
 
Facet api
Facet apiFacet api
Facet api
 
Erpal erp with drupal
Erpal   erp with drupalErpal   erp with drupal
Erpal erp with drupal
 
Drupal 8 theming principles
Drupal 8 theming principlesDrupal 8 theming principles
Drupal 8 theming principles
 
Drupal 7 и history.js или как ajax инфицировать сайт
Drupal 7 и history.js или как ajax инфицировать сайтDrupal 7 и history.js или как ajax инфицировать сайт
Drupal 7 и history.js или как ajax инфицировать сайт
 
Cdn hosting решения для drupal (medium)
Cdn hosting   решения для drupal (medium)Cdn hosting   решения для drupal (medium)
Cdn hosting решения для drupal (medium)
 
Aegir. развертывание и управление большой сетью drupal сайтов
Aegir. развертывание и управление большой сетью drupal сайтовAegir. развертывание и управление большой сетью drupal сайтов
Aegir. развертывание и управление большой сетью drupal сайтов
 
Behat
BehatBehat
Behat
 
что нового в мире Services
что нового в мире Servicesчто нового в мире Services
что нового в мире Services
 

Último

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
Earley Information Science
 
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
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
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
vu2urc
 

Último (20)

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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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
 
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
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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 Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

ознакомления с модулем Entity api

  • 1. Entity API Understanding the Entity API Module Sergiu Savva Drupal developerwearepropeople.com
  • 2. Summary 1. An introduction to entities 2. Entity types 3. Bundles 4. Fields 5. Entity 6. Entity API 7. Entity metadata wrapper 8. Getters ,Setters, Multilingual
  • 3. An Introduction to Entities We can build Entity types, which can make Bundles, to which we can add Fields and then create Entities. Entity types > Bundles > Fields > Entities
  • 4. Entity types Fieldable entities make Drupal eminently flexible. An entity type is a useful abstraction to group together fields. ● Flexible ● Fieldable ● Used by Views and Rules
  • 5. Entity types ● Nodes (content) ● User profiles ● Taxonomy terms ● Comments Some examples of entity types:
  • 6. Entity types ● label - The human-readable name of the type. ● controller class - The name of the class that is used to load the objects. ● fieldable - Set to TRUE if you want your entity type to accept fields being attached to it. ● bundles - An array describing all bundles for this object type. ● view modes - An array describing the view modes for the entity type. You can also build new kinds of entity types if the options above don't suit your needs. Read further about using the hook_entity_info()
  • 7. Bundles Bundles are an implementation of an entity type to which fields can be attached. You can consider bundles as subtypes of an entity type. Bundles for entity type node:
  • 8. Fields Fields can be added to any of the bundles or entity types to help organize their data.
  • 9. Entity An entity would be one instance of a particular entity type such as a comment, taxonomy term, user profile or a bundle such as a blog post, article or product. ● An entity type is a base class ● A bundle is an extended class ● A field is a class member, property, variable or field instance (depending on your naming preference) ● An entity is an object or instance of a base or extended class
  • 10. Relation Entity - Field Entity Fields title body taxonomy some text number Bundles Node Page News title body taxonomy some text number
  • 11. Entity Entity functions from core: entity_get_controller Get the entity controller class for an entity type. entity_get_info Get the entity info array of an entity type. entity_label Returns the label of an entity. entity_language Returns the language of an entity. entity_load Load entities from the database. entity_load_unchanged Loads the unchanged, i.e. not modified, entity from the database. entity_prepare_view Invoke hook_entity_prepare_view(). entity_uri Returns the URI elements of an entity.
  • 12. Core entities entity_get_info($entity_type = NULL) File : common.inc Get the entity info array of an entity type.
  • 14. Entity API (contrib) The project Entity API extends the entity API of Drupal core in order to provide an unified way to deal with entities and their properties. Additionally, it provides an entity CRUD* controller, which helps with simplifying the creation of new entity types. [ CRUD - Create, read, update and delete ]
  • 15. Entity API (contrib) Name Description entity_access Determines whether the given user has access to an entity. entity_create Create a new entity object. entity_delete Permanently delete the given entity. entity_delete_multiple Permanently delete multiple entities. entity_export Exports an entity. ntity_import Imports an entity. entity_load_single A wrapper around entity_load() to load a single entity by name or numeric id. entity_metadata_wrapper Returns a property wrapper for the given data. entity_revision_delete Deletes an entity revision. entity_revision_load Loads an entity revision. entity_save Permanently save an entity. entity_theme Implements hook_theme(). entity_type_is_fieldable Checks whether an entity type is fieldable. entity_view Generate an array for rendering the given entities. entity_get_property_info Get the entity property info array of an entity type.
  • 16. Entity API hooks ● hook_entity_view ● hook_entity_insert ● hook_entity_update ● hook_entity_presave ● hook_entity_delete ● hook_entity_load
  • 18. Why use entity metadata wrappers? ● Makes your code more readable ● Provides a standardised way of accessing field values and entities through an API ● Stops you hard coding the language key into the array lookups ● Stops those nasty PHP warnings when you are trying to access properties that do not exist ● The wrapper autoloads entities (when used in conjunction with the ->value() accessor), which allow you to chain the callbacks
  • 19. Entity metadata wrapper $wrapper = entity_metadata_wrapper('node', $nid); $mail = $wrapper-->author->mail-->value(); $wrapper-->author-->mail-->set('fago@example.com'); $text = $wrapper-->field_text-->value(); $wrapper-->language('de')-->field_text-->value(); $terms = $wrapper-->field_tags-->value(); $wrapper-->field_tags[] = $term; $options = $wrapper-->field_tags-->optionsList(); $label = $wrapper-->field_tags[0]-->label(); $access = $wrapper-->field_tags-->access('edit');
  • 20. Entity metadata wrapper $node = entity_load_single('node',1); $entity_wrapper = entity_metadata_wrapper('node', $node); $entity_wrapper = entity_metadata_wrapper('node', 1); Load OR
  • 21. Entity metadata wrapper Getters $entity_wrapper = entity_metadata_wrapper('node', 1); dpm($entity_wrapper->field_product->raw()); dpm($entity_wrapper->field_product->value());
  • 22. Entity metadata wrapper Getters $entity_wrapper = entity_metadata_wrapper('node', 1); dpm($entity_wrapper->value());
  • 23. Entity metadata wrapper $wrapper = entity_metadata_wrapper('node', 1); $mail = $wrapper->author->mail->value(); $wrapper->author->mail->set('foo@mail.com'); $wrapper->author->mail = 'foo@mail.com'; $wrapper->author->save(); Setters
  • 24. Entity metadata wrapper Multilingual $wrapper = entity_metadata_wrapper('node',1); dpm($wrapper->title_field->value()); dpm($wrapper->language('ro')->title_field->value()); dpm($wrapper->language('ru')->title_field->value());
  • 25. Entity metadata wrapper in life // add the items from the 'show_features' taxonomy $show_features = array(); $features = $series->field_features; if (is_array($features[LANGUAGE_NONE])) { foreach($features[LANGUAGE_NONE] as $tids) { $tid = $tids['tid']; $term = taxonomy_term_load($tid); $featureList[] = $term->name; } } Old approach
  • 26. Entity metadata wrapper in life // add the items from the 'show_features' taxonomy $show_features = array(); foreach ($wrapper->field_features->value() => $feature) { $show_features[] = $feature->name; } Entity metadata wrapper approach