Author: Aaron Klump sourcecode@intheloftstudios.com
Provide a simple and consistent means to interact programatically with entity data, form submissions and other Drupal data across projects and major versions.
You may also visit the project page on Drupal.org.
composer install
; for more information on composer go here.// Create a getter for node entities
$n = data_api('node');
// Load a node entity
$node = node_load(4503);
// Use the getter to pull the first name or default.
// Do not include the language key; language is determined automatically.
$vars['name'] = $n->get($node, 'field_first_name.0.value', '{first name}');
// You can resuse the node getter with a new node. The node getter can be reused as long as the entity type doesn't change.
$node = node_load(345);
$vars['name'] = $n->get($node, 'field_first_name.0.value', '{first name}');
// But to pull data from a different entity type, you can either create a new getter for user entities...
$u = data_api('user');
//... or just reassign the entity type of the original getter to 'user'.
$n->setEntityType('user');
$vars['mail'] = $n->get($GLOBALS['user'], 'mail', '{missing email}');
This will also work on native arrays and objects, and offers a means of supplying defaults with minium code. For more information go here.
// Create a global getter that uses no entity type.
$g = data_api();
// Using a standard array...
$array = array('do' => array('re', 'mi'));
// Access it's elements.
print $g->get($array, 'do.0', 'none'); // === 're'
print $g->get($array, 'do.1', 'none'); // === 'mi'
print $g->get($array, 'do.2', 'none'); // === 'none'; the default
$value = data_api()->get($form_state, 'values.summary', 'none');
The fourth argument is a callable that receives the value and the default, so you can post process the value, e.g.,
$related_node = data_api('node')->get($node, 'field_related_node.0.nid', null, function ($nid, $defaultValue) {
return $nid ? node_load($nid) : $defaultValue;
});
I'm planning a Drupal 8 version which will follow the same patterns so you do not have to relearn a new api.