1

I have loaded a node object in my module, I want to get the single value entered for a specific field (a text field).

I can access it directly with $node->field_position['und'][0]['safe_value'].

Is there a better way to do this? I have looked at field_get_items and field_view_value but I dont want a renderable array or an array at all. Isn't there a way to just return the string value? Having

$items = field_get_items('node', $node, 'field_position');
$position = $items[0][safe_value];

just seems like additional code that doesnt make it any simpler

7

Entity API

Documentation says: The Entity API provides wrapper classes you may use to make dealing with the values of an entities 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. https://drupal.org/node/1021556

    // Create wrapper around the node.
    $wrapper = entity_metadata_wrapper('node', $node);

    // We can do it also using only $nid.
    $wrapper = entity_metadata_wrapper('node', $nid);

    // Get the value of field_name of the node.
    $wrapper->field_name->value();

    // Get the value of field_name of the nodes author's profile.
    $wrapper->author->profile->field_name->value();
    $wrapper->author->profile->field_name->set('New name');
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.