The case is following: I have a custom Content Type with a filed "data_field", for example. I want to have a block on a sidebar that will properly process and display data of this "data_field" field. How can I access that with Drupal API?

P.S. I understand that this problem can be solved with Views in some way, it has an ability of content-specific displaying, but I'm interested in the way it's achieved owing to API.

有帮助吗?

解决方案

To render a field with the default Drupal settings for the content type:

$n = node_load($nid_of_content);
$n = node_view($n);
print render($n['field_somevalue']);

You can specify a node display format as well, eg

$n = node_view($n, 'teaser');

If you want to manipulate field content in a different way, use the raw field value:

$n = node_load($nid_of_content);
$value_you_want = $n->field_data_field_somevalue['und'][0]['value'];

This assumes you're not using any language/translation functionality - the 'und' stands for "undefined" and states that no language is has been explicitly set for the node.

If the field can contain multiple values, iterate through ['und'][0]['value'] to ['und'][x]['value']

The above code displays a raw value for most field types. Use print_r($n->field_somevalue) during development to find out what values are available to you; it depends on the field type. For example, file types give you 'uri' (among others) instead of 'value', text fields also have 'safe_value' which has input format filtering applied, long text fields will have 'summary' and 'safe_summary', &c.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top