Shortest code to find field value for any node in drupal

I used this code in Drupal 7 to get the value of a node field:

$node = node_load($nid);
$rate = $node->field_rate[und][0][value];

How to get value $ratewithout using long array syntax?

After research, I get

$field = field_get_items('node', $node, 'field_rate')
$rate = $field[0]['value'];

But this is still long if I need to get the nnumber of fields.

+4
source share
1 answer

field_get_itemsis the best way to get value because it controls the language for you. Otherwise, you can make a sql query if you want more fields. You can also create a custom function as follows:

    /**
     * @param        $entity_type
     * @param        $entity
     * @param  array $field_names // field_names
     * @param  null  $langcode
     * @return array
     */
 function multi_field_get_items($entity_type, $entity, $field_names = array(), $langcode = NULL){
  $field_values = array();
  foreach ($field_names as $field_name){
    $data =  field_get_items($entity_type, $entity, $field_name, $langcode);
    if(is_array($data) && count($data) > 1){
      foreach ($data as $several_values) {
        $field_values[ $field_name ][] = current($several_values);
      }
    }else if(is_array($data) && count($data) == 1){
      $field_values[ $field_name ] = current(current($data));
    } else {
      $field_values[ $field_name ] = null;
    }
  }
  return $field_values;
}

Example:

$field = multi_field_get_items('node', $node, array('field_rate'));

var_dump($field); // array('field_rate' => 'value of field rate');

If it is a collection, it will return:

array('field_rate' => array('value of field rate 1', 'value of field_rate 2'));
+5
source

Source: https://habr.com/ru/post/1682464/


All Articles