Skip to main content

Developing A Custom Drupal Entity

Chauncey Thorn | Software Architect

September 26, 2013


The introduction of entities in Drupal 7 gave developers nodes, users, taxonomy term and comments. Many developers wonder when it's appropriate to create a custom entity? The answer is, it depends on the project. However, a good example is when a developer needs to expose custom tables and needs to maintain core functionality.  So, the real question is, how as developers, can we create our own custom entities if required? Drupal core provides some functions to work with entities. However, the entity API provides a number of very useful functions:

  • entity_create()
  • entity_save()
  • entity_delete()
  • entity_load()
  • entity_id()
  • entity_export()
  • entity_import()
  • entity_view()
  • entity_access()
  • entity_get_property_info()

Plus every custom entity you create will have it's own Controller that's responsible for all operations on this particular entity (create, edit, delete, view, etc). I've attempted to create a practical implementation of an entity that allows you to see the resulting functionality (CRUD, search, Bulk delete and tests). The entity was developed around a dataset provided here. I've included a drush script that imports the legislators.csv included in the github repo. Also, I've provided an example CasperJS behavioral test and a phpunit test. I've tried to format this blog post as a mini how-to guide with code available as an example. So let's begins. The code for this entity is here: https://github.com/chaunceyt/lawmakers Let's begin by implementing our hook_entity_info(). This will declare our entity and inform Drupal about the custom entity. I've bolded the directives that are highlighted in this post:

/**
 * Implements hook_entity_info().
 */
function lawmakers_entity_info() {
  $lawmakers_entity_info['lawmakers'] = array(
    'label' => t('Lawmakers'),
    'label callback' => 'lawmakers_label_callback',
    'entity class' => 'Lawmakers',
    'controller class' => 'LawmakersController',
    'base table' => 'lawmakers',
    'uri callback' => 'lawmakers_uri',
    'fieldable' => TRUE,
    'entity keys' => array(
      'id' => 'lawmakers_id'
    ),
    'uri callback' => 'entity_class_uri',
    'load hook' => 'lawmakers_load',
    'static cache' => TRUE,
    'admin ui' => array(
      'path' => 'admin/content/lawmakers',
      'controller class' => 'LawmakersUIController',
      'file' => 'includes/lawmakers.admin.inc',
     ),
     'module' => 'lawmakers',
     'access callback' => 'lawmakers_access_callback',
     'bundles' => array(
      'lawmakers' => array(
        'label' => 'Lawmakers',
          'admin' => array(
          'path' => 'admin/structure/lawmakers/manage',
          'access arguments' => array('administer lawmakers'),
         ),
       ),
     ),
     'views controller class' => 'EntityDefaultViewsController',
  );

  return $lawmakers_entity_info;
}

Directive 'label callback':

'lawmakers_label_callback'. This is a standard Entity API label callback that takes a look at our entity class method defaultLabel().

function lawmakers_label_callback($lawmakers, $type) {
  return empty($lawmakers->username) ? 'Untitled Lawmaker' : $lawmakers->username;
}

Directive 'entity class' :

'Lawmakers'. Here we will "extends" the Entity class setting our own defaultUri path.

class Lawmakers extends Entity {
  protected function defaultUri() {
   return array('path' => 'lawmakers/' . $this->identifier());
  }
}

Directive 'controller class':

'LawmakersController'. Here we will override our save() method to deal with the created/changed timestamp.

class LawmakersController extends EntityAPIController {
 /**
  * Override the save method.
  */

public function save($entity, DatabaseTransaction $transaction = NULL) {
 if (isset($entity->is_new)) {
   $entity->created = REQUEST_TIME;
 }
 $entity->changed = REQUEST_TIME;
 return parent::save($entity, $transaction);
 }
}

Directive 'base table':

'lawmakers'. Here we will define our custom table. See lawmakers.install hook_schema().

Directive 'load hook' => 'lawmakers_load'.

Here we will create our own "node_load()" hook. Note the lawmakers_load is just a wrapper for our lawmakers_load_multiple()

function lawmakers_load($lawmakers_id, $reset = FALSE) {
 $lawmakers = lawmakers_load_multiple(array($lawmakers_id), array(), $reset);
 return reset($lawmakers);
}

Directive 'admin ui': 'controller class':

'LawmakersUIController' Here we will extends the EntityDefaultUIController which provides a controller for building an entity overview form.

Directive 'access callback' => 'lawmakers_access_callback'

Here we will create a custom function returning TRUE if the user has access rights to this menu item, and FALSE if not.

function lawmakers_access_callback() {
  if (user_is_anonymous() && !user_access('administer lawmakers entities')) {
   return FALSE;
  }
  else {
   return TRUE;
  }
}

The screenshot below displays the pagination, basic search input options, and bulk operations functionality provided.

screen shot of the admin content list


You can check out the github repo for the complete entity example. Check back later for part two of my blog series. I will explain how to write CasperJS behavioral test for your entities.  In the meantime, enjoy writing custom entities!  


Recommended Next
Development
A Developer's Guide For Contributing To Drupal
Black pixels on a grey background
Development
3 Steps to a Smooth Salesforce Integration
Black pixels on a grey background
Development
Drupal 8 End of Life: What You Need To Know
Woman working on a laptop
Jump back to top