Drupal有很強大的自定義字段的功能,如果我們要將自定義字段的值打印出來,直接 $nianling = $node->field_nianling[LANGUAGE_NONE][0]['value']; 可能會出錯,現在我們來介紹一個更好的方法.
在Drupal獲取一個自定義字段的值最常用的方法是:
$nianling = $node->field_nianling[LANGUAGE_NONE][0]['value'];
不過當field_nianling內容為空時,會出現類似這樣的錯誤:Notice:Undefined index: value in eval(),如果我們在在取值之前加個判斷,如這樣:
- if (isset(field_nianling[LANGUAGE_NONE])) {
- $nianling = $node->field_nianling[LANGUAGE_NONE][0]['value'];
- //Vevb.com
- }
是可以解決問題,但如果字段多時,代碼看起來就不夠簡潔,而且如果自定義字段是列表字段,就有可能還需要根據列表的 key 獲取相應的 value 值。那么有沒有更好的方法來獲取自定義字段的值呢?
Drupal已經給我們提供了一個
- <a href="https://api.drupal.org/api/drupal/modules%21field%21field.module/function/field_get_items/7">field_get_items</a>
函數,原型如下:
- function field_get_items($entity_type, $entity, $field_name, $langcode = NULL)
函數說明:
返回當前語言的此字段項目.
參數:
- $entity_type: The type of $entity; e.g., 'node' or 'user'.
- $entity: The entity containing the data to be displayed.
- $field_name: The field to be displayed.
- $langcode: (optional) The language code $entity->{$field_name} has to be displayed in. Defaults to the current language.
- Return value
- An array of field items keyed by delta if available, FALSE otherwise.
得到了 field_get_items 的返回字段項目,就可以使用:
- <a href="https://api.drupal.org/api/drupal/modules!field!field.module/function/field_view_value/7">field_view_value</a>
來渲染單個項目值:
- field_view_value($entity_type, $entity, $field_name, $item, $display = array(), $langcode = NULL)
- Returns a renderable array for a single field value.
- Parameters
- $entity_type: The type of $entity; e.g., 'node' or 'user'.
- $entity: The entity containing the field to display. Must at least contain the id key and the field data to display.
- $field_name: The name of the field to display.
- $item: The field value to display, as found in $entity->field_name[$langcode][$delta].
- $display: Can be either the name of a view mode, or an array of display settings. See field_view_field() for more information.
- $langcode: (Optional) The language of the value in $item. If not provided, the current language will be assumed.
返回值指定字段的渲染數組
下面是一個顯示 field_jinsheng 字段的例子代碼:
- $jinsheng = field_get_items('node', $node, 'field_jinsheng');
- $output = field_view_value('node', $node, 'field_jinsheng', $jinsheng[0]) ;
- $output = drupal_render( $output);
- print $output;
新聞熱點
疑難解答