3

Let's say we want to modify the body field.

$node->body[LANGUAGE_NONE][0]['value'] = "test";

This will work if the node is language neutral (?)

$node->body[$node->language][0]['value'] = "test";

This will work if the node has the same langauge as the field.

But is this always the case? I found nodes where this is not the case:

(Object) stdClass
...
language (String, 2 characters ) de
...
body (Array, 1 element)
  und (Array, 1 element)
        0 (Array, 5 elements)
            value (String, 4 characters ) test

So if this is a correct node, how can we access the body field value?

6

field_language() returns the field's display language. You should use code similar to the following one:

$language = field_language('node', $node, 'body');
do_something_with($node->body[$language][0]);

Of course, note that field_language() will determine the right display language ('en' or LANGUAGE_NONE or whatever); if you're modifying fields you might want to modify more than one language.

  • Does this mean you'd really need to do foreach($node->field_name as $languaged_field) { ... } to update them all? Is there nothing more elegant? – Charlie Schliesser Feb 7 '12 at 23:36
5

What's about getting the field value with field_get_items()? Really prefer this solution ...

if ($body = field_get_items('node', $node, 'body')) {
  $my_rendered_content = strip_tags(drupal_render(field_view_value('node', $node, 'body', $body[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.