Object Entity API

Categories

Component ID

1925360

Component name

Object Entity API

Component type

module

Maintenance status

Development status

Component security advisory coverage

not-covered

Component created

Component changed

Component body

Description

Object API is a series of classes and methods that allow to write object-oriented code in Drupal.

The core of Object API is a series of Wrappers for common entities (core and provided by common modules):

  • nodes
  • users
  • taxonomies
  • field collections (provided by field_collection)
  • files (provided by file_entity)

These wrappers supply methods such as field getter, setters and printing and support getting by group (defined by field_group).
Wrappers for fields are also supplied:

  • Text
  • Numbers
  • Lists
  • Booleans
  • Term references (from module entityreference)
  • Locations (from module locations)
  • Dates (timestamp, from module date)
  • Entity references (from module entityreference)

Forms are another target of Object API wrappers.

When to use object API

The Object API wrappers have been proved useful in such contexts:

  • Form personalization: (e.g. inside a hook_form_alter)
  • Automatic hidden fields filling: (e.g. inside a hook_node_update)
  • Custom templating (e.g. print templates)
  • PHP code (e.g. PHP fields, actions, or views_php fields)
  • Create object oriented API models (subclassing generic wrappers)

Examples

Construct a a wrapper for a node with known nid (1):

$myNode = new NodeWrapper($nid);

Print a field rendered with a particular bundle display configuration (1):

print $myNode->printField($field_name, "default");

Print a field rendered with a particular bundle display configuration (2):

print $myNode->getField($field_name)->toHTML("default");

Print a field's raw value:

print $myNode->getField($field_name)->getValue();

Print a field's raw label

print $myNode->getField($field_name)->getLabel();

Set a field's value (1):

print $myNode->setFieldValue($field_name, $new_value);
$myNode->save();

Set a field's value (2):

print $myNode->getField($field_name)->setValue($new_value);
$myNode->save();

Unpublish a node:

$myNode->unpublish();
$myNode->save();