18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Working with Content<br />

Note here as well that we're explicitly declaring the aid field of the revision table<br />

to be a foreign key to the aid field of the artwork table. Although <strong>Drupal</strong> does not<br />

leverage foreign key information itself, other modules may do so. By convention,<br />

tables in <strong>Drupal</strong> should be singular nouns.<br />

With these two tables defined in artwork_schema(), <strong>Drupal</strong> will automatically<br />

create the corresponding tables for us in the database when the module is first<br />

enabled. If our module is uninstalled completely, it will also take care of removing<br />

them for us.<br />

Declaring our entity<br />

There are two parts to telling <strong>Drupal</strong> about our new entity. The first is another<br />

definition hook called hook_entity_info(). This hook tells <strong>Drupal</strong> about the<br />

entity or entities we're providing, and also provides the Field UI system with the<br />

information it needs to allow us to attach fields to entities—more on that later. The<br />

second part is a "controller class", which is a PHP class that will be responsible for<br />

loading and, in our case, creating, saving, and deleting our artwork.<br />

<strong>Drupal</strong> includes a controller class called <strong>Drupal</strong>DefaultEntityController that<br />

handles the most common case, which we will be emulating. It is extremely basic,<br />

however, and only handles loading of objects. Fortunately it is very easy to subclass<br />

the default controller and add our own functionality so that is precisely what we<br />

will do.<br />

A controller is a loader object for an entity. All entity types must have<br />

a controller, but many can use the default. Different controllers may<br />

require additional keys on an entity definition.<br />

The entity declaration<br />

First let's tell <strong>Drupal</strong> about our entity type using hook_entity_info():<br />

/**<br />

* Implements hook_entity_info().<br />

*/<br />

function artwork_entity_info() {<br />

$return['artwork'] = array(<br />

'label' => t('Artwork'),<br />

'controller class' => 'ArtworkController',<br />

'base table' => 'artwork',<br />

'revision table' => 'artwork_revision',<br />

'uri callback' => 'artwork_uri',<br />

[ 156 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!