How to Use Entity metadata wrappers (Entity API) in Drupal7)
Note: Due to the limited level of English https://www.drupal.org/documentation/entity-metadata-wrappers, some sentences may not be very understanding in place, if you have doubts, please refer to the source documentation.
Using the wrapper packaging class, you can easily obtain and set the field values and content in a consistent programming manner.
For example, when we need to obtain the value of a field from a node, we often obtain the value in the drupal object using the following method:
$ Node-> field_number [LANGUAGE_NONE] [0] ['value']
Although this method works normally in most cases, it is not ideal. For example, the user requires that the page display different languages or the 'value' in the above field does not exist or is it an image or file field?
Using the metadata wrapper provided by the Entity module, we can easily obtain the value of a field without worrying about it, just like this:
$ Node_wrapper-> field_number-> value ();
All Entities entity types in Drupal have certain types of labels. The label of object type is usually a user-friendly character name. For example, all node types have the attribute of title and all users have the user name, if it is a standard object type, it is hard to know how to handle these labels correctly. Metadata wrapper provides a unified method to obtain information of different object types. For example:
// Uniied way of getting $ node-> title, $ user-> name ,... $ wrapper-> label (); // uniied way of getting $ node-> nid, $ user-> uid ,... $ wrapper-> getIdentifier (); // uniied way of getting $ node-> type ,... $ wrapper-> getBundle ();
Examples (example)
Some wrapper packaging classes can be used to easily obtain and set values.
To wrap an object, you can use programmatic functions as follows:
$ Wrapper = entity_metadata_wrapper ('node', $ node );
Or you can also use Entity: wrapper () after the Entity API 7. X-1.6 ().
$ Wrapper = $ entity-> wrapper ();
However, this is only true if the $ entity object uses the Entity class provided by the Entity API module.
Wrapper supports chained operations to obtain object attributes. For example, to obtain the mail address information of the author of a node:
$ Wrapper-> author-> mail-> value ();
Update the user's mail address:
$ Wrapper-> author-> mail-> set ('Sepp @ example.com ');
Alternatively, you can write the statement as follows:
$ Wrapper-> author-> mail = 'Sepp @ example.com ';
Wrappers always returns a descriptive data object, which can be obtained from a wrapper through entity_get_property_info:
$ Mail_info = $ wrapper-> author-> mail-> info ();
You can obtain the value of the text and perform the cleanup operations as follows:
$ Wrapper-> title-> value (array ('sanitize' => TRUE ));
Generally, the title of a node is of the plain text type, but the body field may contain tags and other harmful content. How can I obtain the body Field and filter it accordingly?
$ Wrapper-> body-> value (array ('decode' => TRUE ));
In this way, the cleaned or filtered data is always obtained and presented to the user. However, if you really need to obtain raw data that is not processed, you can:
$ Wrapper-> body-> raw ();
For more examples, see the tests file in the Entity module.
Working with lists (use list)
A list of multi-value data containing wrappers, such as a multi-value reference field, can be iterated as follows:
$ 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 ();}
You can set values for a multi-value list in multiple ways:
You can set the entire value as an array:
$ 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 );
You can also use the square brackets of the standard array to set values for fields:
// 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 obtain the array data of the field, process it, and return:
// Add to a list using the whole array. $ containing_node = node_load ($ nid); $ w_containing_node = cursor ('node', $ containing_node); $ curr_list = $ w_containing_node-> cursor-> value (); if (! $ Curr_list) $ curr_list = array (); $ curr_list [] = $ new_nid; $ w_containing_node-> nodes-> set ($ curr_list); $ w_containing_node-> save ();
Deleting values (delete value)
Wrapper does not provide the-> delete () method to delete the value of a field. To delete the value of a field correctly, do the following:
// 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 () (use the value (), set (), and save () methods)
We first get the value of a field, then use set () to set the value for it and save it:
$ Node_wrapper = entity_metadata_wrapper ('node', $ node); $ var = $ node_wrapper-> field_number-> value () + 1; $ node_wrapper-> field_number-> set ($ var); $ node_wrapper-> save ();
To save the value of a file or image field, you need to pass the key name 'fid' to the set () function. For example:
$ Containing_node = node_load ($ nid); $ w_containing_node = entity_metadata_wrapper ('node', $ containing_node); // Load the file object any in way $ file_obj = file_load ($ fid ); $ w_containing_node-> field_attachment_content-> file-> set ($ file_obj );//.. or pass an array with the fid $ w_containing_node-> field_attachment_content-> set (array ('fid' => $ fid); $ w_containing_node-> save ();
Example of creating a node :( create a node)
You need to set the content type and user ID of the node for the new node, and then you can use the object of entity_metadata_wrapper () to process it:
// Create an Entity. $ node = entity_create ('node', array ('type' => 'image'); // Specify the author. $ node-> uid = $ user-> uid; // Create a Entity Wrapper of that new Entity. $ emw_node = entity_metadata_wrapper ('node', $ node); // Set a title and some text field value. $ emw_node-> title = 'Test node'; $ emw_node-> field_text_field = 'field value text'; // And save it. $ emw_node-> save ();
Get first value of multifield (multiple-value field) (obtain the first value of a multi-value field)
You only need to add an index (array subscript) after the field name. For example, you can obtain the first value:
$ First_name = $ wrapper-> field_tags [0]-> name-> value ();
Example using field collections (Example of using field collections)
// Populate the fields. $ ewrapper = entity_metadata_wrapper ('node', $ node); $ ewrapper-> nodes-> 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 (exception handling)
When you use entity_metadata_wrapper (), it is recommended to put the code into the try... catch code block. In this way, you can avoid interruptions when the program is abnormal, and you can use watchdog in the catch code block to record error logs in the background for debugging. For example:
Try {$ node_wrapper = entity_metadata_wrapper ('node', $ node); $ price = $ node_wrapper-> field_product-> field_price-> value ();} catch (EntityMetadataWrapperException $ exc) {watchdog ('Module _ name', 'access '. _ FUNCTION __. '() <pre> '. $ exc-> getTraceAsString (). '</pre>', NULL, WATCHDOG_ERROR );}
Get Start-date and End-date values from Date fields (Get the Start and End dates of the date field)
If you have a Date field (provided by the Date module), you can obtain the start/end Date as follows:
$ 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'];
Alternatively, you can:
$ Wrap_node = entity_metadata_wrapper ('node', $ node); $ start_date = $ wrap_node-> field_my_data-> value (); $ end_date = $ wrap_node-> field_my_data-> value2-> value ();
Getting information about properties and fields (get information about attributes and fields)
The getPropertyInfo () method can return variable information about attributes and fields, but the corresponding fields must be passed to the entity_metadata_wrapper () method.
// Wrapper for entity type 'node', but not specific bundle. $ wrapper = entity_metadata_wrapper ('node'); // Info will contain information only about properties and not about fields. $ info = $ this-> getPropertyInfo ();
Now add the binding type:
// Wrapper for entity type 'node' with specific bundle 'page' specified. $ wrapper = entity_metadata_wrapper ('node', NULL, array ('bundle' => 'Page'); // Info will contain information about both properties and fields. $ info = $ this-> getPropertyInfo ();
Debugging or introspecting wrappers (Debugging)
To obtain a list of all available variables of an Entity wrapper, you can use dpm () for output (devel module needs to be installed and enabled ):
Dpm ($ wrapper-> getPropertyInfo ());
However, this does not give you any attribute values. You can write a piece of code to output debugging information:
Function _ wrapper_debug ($ w) {$ values = array (); foreach ($ w-> getPropertyInfo () as $ key => $ val) {$ values [$ key] = $ w-> $ key-> value ();} return $ values ;}
Then use it in your code:
Dpm (_ wrapper_debug ($ some_wrapped_object ));