php - shortest code to find the field value of any node in drupal -


i have been using code in drupal 7 value of node's field:

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

how $rate value without using long array syntax?

after research

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

but still long if need n number of fields.

field_get_items best way value because manage language. otherwise can make sql query if want more field. can create custom function :

    /**      * @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 $field_name){     $data =  field_get_items($entity_type, $entity, $field_name, $langcode);     if(is_array($data) && count($data) > 1){       foreach ($data $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 collection, return :

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

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -