Attach Extra or Pseudo Fields to any Entity in Drupal
In Drupal 7 you can push Extra Fields in any fieldable Entity (e.g. node, user). Extra fields can be ordered as a normal field or disabled on the display settings page of the enitity. They are great when you want to push content in your entity, that need some logic before they can be displayed.
Start by creating your own Drupal 7 module. That is beyond the scope of this blog post, you can find a good reference on the Drupal site.
Now you are ready to use two hooks. The first one defines the extra field you want to add.
/**<br> * Implements hook_field_extra_fields().<br> */<br>function HOOK_field_extra_fields() {<br> $extrafield_name = 'my_field';<br> foreach (array('page', 'article') as $node_type) {<br> $extra['node'][$node_type]['display'][$extrafield_name] = array(<br> 'label' => t('Some freaking title'),<br> 'description' => t('A serious description.'),<br> 'weight' => 50, // default weight, can be changed on display form by site-builder.<br> );<br> }<br> return $extra;<br> }
In this example I've added the pseudo field 'my_field' to the entity node on the bundles 'page' and 'article'. Note: Replace HOOK in the function name with your own module name!
The next hook will add the content.
/**<br> * Implements hook_node_view().<br> * Also HOOK_entity_view() can be used.<br> */<br>function HOOK_node_view($node, $view_mode, $langcode) {<br> $extrafields = field_info_extra_fields('node', $node->type, 'display');<br> $extrafield_name = 'my_field';<br> if (isset($extrafields[$extrafield_name])<br> && isset($extrafields[$extrafield_name]['display'][$view_mode]['visible'])<br> && $extrafields[$extrafield_name]['display'][$view_mode]['visible']) {<br> // Your logic here.<br> $node->content[$extrafield_name] = 'Build array or string with content';<br> }<br>}
Put in your own logic and enjoy!