Drupalcon SF: How Drupal 7 Fields are changing the way you write modules

By May 1, 2010Web Development

How Drupal 7 Fields are changing the way you write modules

In Drupal 6, you used hook_nodeapi() and created a table

In Drupal 7, you create a Field.

Fields are shared between entities. Define once, reuse on different things (nodes, comments, users).

Anatomy

  • Schema = storage
  • Widget = how to edit. the editor’s interface.
  • Formatter = how to display the contents of the field
  • Settings = global or per-instance
  • Bundle = entity type

Field API

Entities (are the new nodes)

  • high level object
  • fieldable (can have fields attached)
  • revisionable (can have revisions)
  • can have bundles (sub-types. content types are a current example.)
  • can have a URI
  • can have build modes (Full, Teaser, RSS, Tile, etc.)

Entity API

  • hook_entity_info()
  • hook_entity_ [load | insert | update] (no delete)
  • entity_load (no save or delete)

Entity API module fills in the missing pieces, such as hook_entity_delete() and entity_save().

Application

Nodes and Comments can share the definition and data of the same field.

Creating an Issue tracker. This was demonstrated in the session.

  • Used an custom content type of “Issue”
  • Added a “Severity” field in content type and in comment.
  • Custom Module: sets default value, adds checkbox to content type settings, updates value of node when submitting the comment.

Don’t use nodes for anything that is not content. (This might be a big change in thinking.)

  • Create your own entities instead of creating custom content types.
  • Examples: Group, Product.

If extending an existing content type, or something defined by another module, use entities. Don’t create your own tables; let the entities API handle that for you.

Rely on the Views module to display your entities. (Views is not yet aware of alternate data storage engines, such as MongoDB and Flickr.)

Upgrade path

  1. Start with doing a simple upgrade of existing modules.
  2. Next, start rethinking how to make better use of fields, entities, and bundles.

Leave a Reply