Skip to content

Instantly share code, notes, and snippets.

@msankhala
Created July 30, 2014 08:08
Show Gist options
  • Save msankhala/e371c202faefa0c47356 to your computer and use it in GitHub Desktop.
Save msankhala/e371c202faefa0c47356 to your computer and use it in GitHub Desktop.
The Entity API provides wrapper classes you may use to make dealing with the values of an entity's properties and fields easier. Wrappers make it easier to get and set the values of fields and properties as well as to programmatically retrieve additional information about these elements and iterate over lists of values in a consistent manner. Fo…
<?php
$node->field_number[LANGUAGE_NONE][0]['value']
?>
//Using metadata wrappers from the entity module we can access this information like so:
<?php
$node_wrapper->field_number->value();
?>
// How about an example of making things consistent? All Drupal entities have a label of some sort. A string that can be treated as the canonical human readable name of an entity. All nodes have a title property and all user accounts have a name property. Given a standard Drupal entity it can be hard to know which property should be treated as the label. Metadata wrappers provide us with a consistent way of getting at this kind of information for any entity.
<?php
// Unified way of getting $node->title, $user->name, ...
$wrapper->label();
// Unified way of getting $node->nid, $user->uid, ...
$wrapper->getIdentifier();
// Unified way of getting $node->type, ...
$wrapper->getBundle();
?>
//Working with lists
//A list value that contains wrappers, such as a multi-valued reference field, can be iterated over thus:
<?php
$wrapper = entity_metadata_wrapper('node', $node);
foreach ($wrapper->field_taxonomy_terms->getIterator() as $delta => $term_wrapper) {
// $term_wrapper may now be accessed as a taxonomy term wrapper.
$label = $term_wrapper->label->value();
}
?>
//Setting values or adding values to a list value, such as a multi-valued entity reference field, can be accomplished in several ways.
//You can set an array as the whole value:
<?php
$containing_node = node_load($nid);
$w_containing_node = entity_metadata_wrapper('node', $containing_node);
$nids_to_set = array(42, 23);
$w_containing_node->field_entity_reference_field->set($nids_to_set);
?>
//The field wrapper can be appended to using square bracket syntax, the same as when working with a normal array:
<?php
// Setting or adding to a list using square bracket syntax
$containing_node = node_load($nid);
$w_containing_node = entity_metadata_wrapper('node', $containing_node);
// This appends to what is already there, just like a normal array.
$w_containing_node->field_entity_reference_field[] = 42;
$w_containing_node->field_entity_reference_field[] = 23;
?>
//Finally, you can get the array out of the field, manipulate it, and set it back:
<?php
// Add to a list using the whole array.
$containing_node = node_load($nid);
$w_containing_node = entity_metadata_wrapper('node', $containing_node);
$curr_list = $w_containing_node->field_entity_reference_field->value();
if (!$curr_list)
$curr_list = array();
$curr_list[] = $new_nid;
$w_containing_node->field_entity_reference_field->set($curr_list);
$w_containing_node->save();
?>
//Deleting values
//To delete values, there is no ->delete() method on the fields. You have to use this way to correctly delete a value:
<?php
// Using an empty ->set(NULL) removes the value - without NULL you'll get a PHP notice that set($value) requires 1 parameter.
$wrapper->field_data->set(NULL);
// And handles correctly the deltas when using multiple values fields
$wrapper->field_data[$delta]->set(NULL);
?>
Example of using value(), set() and save()
<?php
$node_wrapper = entity_metadata_wrapper('node', $node);
$var = $node_wrapper->field_number->value() + 1;
$node_wrapper->field_number->set($var);
$node_wrapper->save();
?>
//Get first value of multifield (multiple-value field)
//Just set value index directly after field name:
<?php
$first_name = $wrapper->field_tags[0]->name->value();
?>
//Example using field collections
<?php
// Populate the fields.
$ewrapper = entity_metadata_wrapper('node', $node);
$ewrapper->field_lead_contact_name->set($contact_name);
$ewrapper->field_lead_contact_phone->set($contact_phone);
$ewrapper->field_lead_contact_email->set($contact_email);
// Create the collection entity and set it's "host".
$collection = entity_create('field_collection_item', array('field_name' => 'field_facilities_requested'));
$collection->setHostEntity('node', $node);
// Now define the collection parameters.
$cwrapper = entity_metadata_wrapper('field_collection_item', $collection);
$cwrapper->field_facility->set(intval($offset));
$cwrapper->save();
// Save.
$ewrapper->save();
?>
//Exceptions
/* It's recommended to wrap code in try...catch section when you work with entity_metadata_wrapper() to catch EntityMetadataWrapperException.
You can add hints for you in watchdog for debugging errors. For example function name or line number. Example: */
<?php
try {
$node_wrapper = entity_metadata_wrapper('node', $node);
$price = $node_wrapper->field_product->field_price->value();
}
catch (EntityMetadataWrapperException $exc) {
watchdog(
'MODULE_NAME',
'See ' . __FUNCTION__ . '() <pre>' . $exc->getTraceAsString() . '</pre>',
NULL, WATCHDOG_ERROR
);
}
?>
/*Get Start-date and End-date values from Date fields
If you have Date fields (provided by Date module) you can get Start/End values from a field in this way: */
<?php
$wrap_node = entity_metadata_wrapper('node', $node);
$start_date = $wrap_node->field_my_data->value()['value'];
$end_date = $wrap_node->field_my_data->value()['value2'];
?>
//or alternatively:
<?php
$wrap_node = entity_metadata_wrapper('node', $node);
$start_date = $wrap_node->field_my_data->value->value();
$end_date = $wrap_node->field_my_data->value2->value();
?>
/*Debugging or introspecting wrappers
To get a list of all available properties of a(n) (entity)wrapper, you can use the following snippet (requires the devel module to be installed and enabled): */
<?php
dpm($wrapper->getPropertyInfo());
?>
//But this doesn't give you any of the property values.
//To be able to see the values you can write your own helper to debug wrapped objects:
<?php
function _wrapper_debug($w) {
$values = array();
foreach ($w->getPropertyInfo() as $key => $val) {
$values[$key] = $w->$key->value();
}
return $values;
}
?>
//And then use it in your code:
<?php dpm(_wrapper_debug($some_wrapped_object)); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment