SlideShare a Scribd company logo
Entities in Drupal 7
    Drupalcamp Arad 2012
About me
Senior LAMP developer at Pitech+plus
Drupal projects worked on:

  http://www.louvre.fr

  http://www.cartier.us
Module contributor:
Taxonomy revisions: http://drupal.org/project/taxonomy_revision
Maxlength widget for textareas: http://drupal.org/project/maxlength_js_widget


drupal.org profile:
http://drupal.org/user/350126
IRC nickname: skipyT
Twitter: @ztasnadi
Summary

 short introduction to entities

 declaring an entity

 entity API

 entity properties

 fieldable entities

 entity metadata wrappers

 entity class and the entity controller

 entity field queries
Entities

           What is an entity?
               A data unit!
  A data unit which Drupal is aware of!
          Stored Anywhere...

             Entities in core:
    node = entity content type = bundle
taxonomy term = entity vocabulary = bundle
     and others like files, vocabularies.
Introduction to Entities
All of the entities are:
Loadable
Identifiable

Can be stored anywhere.
Also they can be fieldable.
Declaring an entity


 Implement hook_entity_info()

 Specify the controller class
/**
 * Implements hook_entity_info().
 */
function drupalcamp_entity_info() {
  $return = array(
    'profile' => array(
      'label' => t('Profile'),
      'entity class' => 'ProfileEntity',
      'controller class' => 'EntityAPIController',
      'module' => 'drupalcamp',
      'base table' => 'profile',
      
Declaring an entity
      'access callback' => 'drupalcamp_profile_access',
      'bundles' => array(
        'profile' => array('label' => 'Profile'),
      ),
      'entity keys' => array(
        'id' => 'id',
      ),
    ),
  );
 
  return $return;
}
Declaring an entity

Implement hook_schema()
/**
 * Implements hook_schema().
 */
function drupalcamp_product_schema() {
  $schema = array();
 
  $schema['profile'] = array(
    'description' => "Base table of the profile entity.",
    'fields' => array(
      'id' => array(
        'description' => 'The primary id of a profile.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      
Declaring an entity


    'created' => array(
        'description' => 'The Unix timestamp when 
the profile was created.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'primary key' => array('id'),
  );
 
  return $schema;
}
Declaring an entity


And now you can use functions from core like:
entity_load();
entity_get_info();
entity_get_controller();
But this is not enough!
Let's check Entity API...
Entity API

Assists us interacting with entities.

entity_create()
entity_access()
entity_view()
entity_save()
entity_delete()
entity_load_single()
entity_get_property_info()
entity_metadata_wrapper()
Entity API

Provides a base entity class and a
base entity controller class.

Entity
EntityAPIController

Supports revisions, database
transactions, methods for create,
delete, load, etc.
Provides unified CRUD interface
Entity API
Fieldable entities


    Entities are fieldable if we set:
'fieldable' = TRUE, 
//in hook_entity_info()


    Bundles are like content types for nodes


  Check the entity bundle plugin also: 
http://drupal.org/project/entity_bund
le_plugin
Entity properties


 Unified access to entity data

 Validation

 Access information

Several contrib modules are using it:

 Entity views

 Rules

 Entity tokens

 Search API

 WSClient

 VBO, OG, Drupal commerce
Entity properties
In hook_entity_property_info()
And hook_entity_property_info_alter()

$properties['mail'] = array(
  'label' => t("Email"),
  'type' => 'text',
  'description' => t("The email address of ..."),
  'setter callback' => 'entity_property_verbatim_set',
  'validation callback' => 'valid_email_address',
  'required' => TRUE,
  'access callback' => 'user_properties_access',
  'schema field' => 'mail',
);
Entity properties
Example of entity property use:

/**
 * Implements hook_entity_property_info().
 */
function drupalcamp_entity_property_info_alter(&$entity_info) 
{
  $entity_info['drupalcamp_product_display']['properties']
['sold_online'] = array(
    'label' => t('Product sold online'),
    'type' => 'list<text>',
    'options list' => 'drupalcamp_sold_online_options_list',
    'description' => t('A flag indicating whether or not the 
product is sold online.'),
    'getter callback' => 'drupalcamp_sold_online_getter',
    'computed' => TRUE,
  );
}
Entity wrappers
$wrapper = entity_metadata_wrapper('node', $node);
$mail = $wrapper­>author­>mail­>value();
$wrapper­>author­>mail
  ­>set('ztasnadi@pitechplus.com');
$text = $wrapper­>field_text­>value();
$wrapper­>language('ro')­>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 class

We can use the entity class methods
to avoid to introduce new
implementations for:

 hook_entity_presave

 hook_entity_insert

 hook_entity_update


 Or to do custom methods like entity
health check, tagging, etc.
Entity controller
Example of usage:


 During hook_cron we want to update,
touch multiple entities.

Don't forget to call the resetCache
and the mark to reindex if you are
updating the entities. Good example
is when you are enabling several
entities based on their publication
date.
Entity field queries
$query = new EntityFieldQuery();
$query­>entityCondition('entity_type', 'profile');
$query­>entityCondition('bundle', 'community_profile');
$query­>entityCondition('id', 2, '<>');

$query­>propertyCondition('created_at', 
    time() ­ 3600, '<');
$query­>propertyCondition('user_id', $user­>uid);

$query­>fieldCondition('field_taxonomy_category',     
    'target_id', $term­>tid);
$query­>fieldCondition('field_taxonomy_category', 
    'target_type', 'watches');

$query­>range(0, 10)
  ­>addMetaData('account', user_load(1)); // Run the 
query as user 1.

// Other methods: count, propertyOrderBy, age 
(FIELD_LOAD_CURRENT, FIELD_LOAD_REVISION)
Entity field queries

$result = $query­>execute();

if (!empty($result['profile'])) {
  $profiles = entity_load('profile',    
     array_keys($result['profile']));
}

// The above example works only if the $query age 
is set to FIELD_LOAD_CURRENT, which is the default 
value. For FIELD_LOAD_REVISION the results are 
keyed by the revision id.
And the guy is Charles Darwin
and not Santa, because we are:

More Related Content

What's hot

Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Fabien Potencier
 
Advanced php
Advanced phpAdvanced php
Advanced php
hamfu
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
Fabien Potencier
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
Fabien Potencier
 

What's hot (20)

Drupal 8: Entities
Drupal 8: EntitiesDrupal 8: Entities
Drupal 8: Entities
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Drupal 8: Routing & More
Drupal 8: Routing & MoreDrupal 8: Routing & More
Drupal 8: Routing & More
 
Field api.From d7 to d8
Field api.From d7 to d8Field api.From d7 to d8
Field api.From d7 to d8
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Dependency Injection in Laravel
Dependency Injection in LaravelDependency Injection in Laravel
Dependency Injection in Laravel
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
J query1
J query1J query1
J query1
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
 
Advanced php
Advanced phpAdvanced php
Advanced php
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
J query
J queryJ query
J query
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
 
Doctrine for NoSQL
Doctrine for NoSQLDoctrine for NoSQL
Doctrine for NoSQL
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 

Similar to Entities in drupal 7

ознакомления с модулем Entity api
ознакомления с модулем Entity apiознакомления с модулем Entity api
ознакомления с модулем Entity api
DrupalCamp Kyiv Рысь
 
Developing your first application using FI-WARE
Developing your first application using FI-WAREDeveloping your first application using FI-WARE
Developing your first application using FI-WARE
Fermin Galan
 

Similar to Entities in drupal 7 (20)

Drupal 7 Entity & Entity API
Drupal 7 Entity & Entity APIDrupal 7 Entity & Entity API
Drupal 7 Entity & Entity API
 
Entity api
Entity apiEntity api
Entity api
 
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
 
Understanding the Entity API Module
Understanding the Entity API ModuleUnderstanding the Entity API Module
Understanding the Entity API Module
 
Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019
 
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)
 
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
 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
 
Drupal 8 entities & felds
Drupal 8 entities & feldsDrupal 8 entities & felds
Drupal 8 entities & felds
 
The state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon DublinThe state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon Dublin
 
Drupal 8, Where Did the Code Go? From Info Hook to Plugin
Drupal 8, Where Did the Code Go? From Info Hook to PluginDrupal 8, Where Did the Code Go? From Info Hook to Plugin
Drupal 8, Where Did the Code Go? From Info Hook to Plugin
 
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
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Migrare da symfony 1 a Symfony2
 Migrare da symfony 1 a Symfony2  Migrare da symfony 1 a Symfony2
Migrare da symfony 1 a Symfony2
 
[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
 
ознакомления с модулем Entity api
ознакомления с модулем Entity apiознакомления с модулем Entity api
ознакомления с модулем Entity api
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
Developing your first application using FI-WARE
Developing your first application using FI-WAREDeveloping your first application using FI-WARE
Developing your first application using FI-WARE
 
Widget Tutorial
Widget TutorialWidget Tutorial
Widget Tutorial
 

Recently uploaded

Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 

Recently uploaded (20)

Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 

Entities in drupal 7