Drupal Entity API

Nguyen Tien Si

GO1

Agenda

  • What's entity?
  • Entity API
  • EntityFieldQuery
  • QA?

What's entity?

An entity would be one instance of a particular entity type such as a comment, taxonomy term or user profile or a bundle such as a blog post, article or product.

 

You can use entity_load() to load any entity

Entity in Object-Oriented

  • An entity type is a base class
  • A bundle is an extended class
  • A field is a class member, property, variable or field instance
  • An entity is an object or instance of a base or extended class

Is Drupal support ORM?

<?php

// Regular SQL:
$result = db_query("SELECT uid, name, status, created, access 
 FROM {users} u WHERE uid <> 0 LIMIT 50 OFFSET 0");

// Drupal DB API:
// Create an object of type SelectQuery
$query = db_select('users', 'u');
 
// Add extra detail to this query object: a condition, fields and a range
$query
  ->condition('u.uid', 0, '<>')
  ->fields('u', array('uid', 'name', 'status', 'created', 'access'))
  ->range(0, 50);

?>

Entity API

This module extends the entity API of Drupal core. It provides an entity CRUD controller, which helps simplifying the creation of new entity types.

 

Entity API module the missing pieces are added, includes: 

  • entity_create()
  • entity_save() 
  • entity_delete()
  • entity_view()
  • entity_access()

Entity API: Features

  • Providing a new entity type (support CRUD)
  • Make an entity type exportable
  • Make an entity revision-able
  • Viewing entities
  • Making use of the admin UI
  • Documentation

 

Declaring an entity

<?php

/**
 * Implements hook_entity_info().
 */
function entity_test_entity_info() {
  return array(
    'entity_test' => array(
      'label' => t('Test Entity'),
      'plural label' => t('Test Entities'),
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIController',
      'base table' => 'entity_test',
      'entity keys' => array(
        'id' => 'id',
      ),
      ...
    ),
  );
}

Entity Metadata Wrappers

<?php
 $node->field_number[LANGUAGE_NONE][0]['value'] 
?>

Using metadata wrappers from the entity module we can access this information like so:

<?php
 $node_wrapper->field_number->value(); 
?>

More example

<?php

// Get the entity object back out of the wrapper.
$wrapper = entity_metadata_wrapper('node', $nid);
$node    = $wrapper->value();

?>
<?php

//Working with Text field data.

// OLD & BUSTED: Field API arrays
$l = $node->langugage;
$old_value = $node->field_my_text[$l][0]['value'];
$node->field_my_text[$l][0]['value'] = 'new value';
 
// New: New way
$old_value = $wrapper->field_my_text->value();
$wrapper->field_my_text = 'new value';

<?php

// Working with Longtext field data.
// Array of: value, safe_value, format, 
// and optionally summary + safe_summary.
$wrapper->body->value();
// Filtered value.
$wrapper->body->value->value();  
// Unfiltered value.
$wrapper->body->value->raw();    
// The selected text format.
$wrapper->body->format->value(); 
$wrapper->body->value = 'new value';

EntityFieldQuery

The EntityFieldQuery API lets you fetch information about entities (nodes, users, taxonomy terms et cetera) from Drupal without actually building SQL queries.

Query Builder

<?php

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_news_types', 'value', 'spotlight', '=')
  ->fieldCondition('field_photo', 'fid', 'NULL', '!=')
  ->fieldCondition('field_faculty_tag', 'tid', $value)
  ->fieldCondition('field_news_publishdate', 'value', $year . '%', 'like')
  ->fieldOrderBy('field_photo', 'fid', 'DESC')
  ->range(0, 10)
  ->addMetaData('account', user_load(1)); // Run the query as user 1.

$result = $query->execute();
<?php
function mymodule_superblock() {
  $query = new EntityFieldQuery();
  $result = $query
    ->entityCondition('entity_type', 'node')
    ->fieldCondition('field_categories', 'tid', array('12','13'), 'IN')
    ->propertyCondition('status', NODE_PUBLISHED)
    ->addTag('random')
    ->range(0,5)
    ->execute();
}

/**
 * Implements hook_query_TAG_alter().
 */
function mymodule_query_random_alter($query){
  $query->orderRandom();
}

Query Alter via TAG

References

  • https://www.drupal.org/node/1343708
  • https://www.drupal.org/project/entity
  • https://www.drupal.org/node/1261744
  • https://www.drupal.org/node/878784

QA?

Drupal Entity API

By Nguyen Tien Si

Drupal Entity API

  • 1,440