Module Development

Override the Entity Controller for Better Rendering and Saving for Drupal 7

Check your version

This tutorial covers a topic in Drupal 7 which may or may not be the version you're using. We're keeping this tutorial online as a courtesy to users of Drupal 7, but we consider it archived.

Alternate resources

Sprout Video

So far we’ve seen that you can use entity_load and entity_view to display your entity. But what if you want more control over how your content gets rendered? In this lesson we’ll take a look at overriding the buildContent() method of our entity controller to spruce up the output a bit. We'll also overrid the save() method of the controller in order to populate the created_at and updated_at fields automatically when saving a video entity.

Note: In order to improve upon the security of the code in this lesson you'll want to make sure you're escaping all user input properly. The following code:


$build['embedcode'] = array(
      '#type' => 'markup',
      '#markup' => '<iframe width="560" height="315" src="http://www.youtube.com/embed/'. $entity->embedcode . '" frameborder="0" allowfullscreen></iframe>',
    );

Should be updated to use the check_url() function when outputting $entity->embedcode to ensure that user entered content is safe for use in the context of a URL.


$build['embedcode'] = array(
      '#type' => 'markup',
      '#markup' => '<iframe width="560" height="315" src="http://www.youtube.com/embed/'. check_url($entity->embedcode) . '" frameborder="0" allowfullscreen></iframe>',
    );