Drupal: Cross-Linking Custom Content-Types via Custom Fields using Entity API and Field API

Scenario: a book where pages have multiple subpages as tabs, e.g. a Drupal Book content-type with documentation of RESTful API Resources, where each API Resource Book page is linked to multiple Code Example content-types, ordered in a tabbed page with one Code Example per language tab.

drupal_crosslinks_entity_reference

Drupal 7 and 8 has a set of abstraction layers, abstracting nodes to Entity Type, Bundle, and Field. A Node is an Entity Type, just like Taxonomy, Comment or User, or Book, Article, Blog Post etc. An Entity is an implementation instance of an Entity Type. An Entity Type is defined in a Bundle that has a collection of Fields.

Create a new ‘Entity Type’ named ‘Code Example’. Install the Entity Reference module. On the Book page, click Manage Fields, add a Field to the Book page Entity Type of type Entity Reference with multiple selections. Create a few Code Examples for the Book page node. On the instance or node of the Book page, select the Entity References of type Code Examples.

Create a Taxonomy with a hierarchy of coding languages. In the Code Example entity type, click Manage Fields and add a field based on the coding languages taxonomy. The tabs in the Book page will be labeled by code language, e.g. Java, JavaScript, Objective-C, etc.

Then, to use JQuery UI.tabs we can create a tabular page with Code Examples per language, crosslinked to entities or nodes of type Book Page.

<?php
drupal_add_library('system', 'ui.tabs');
drupal_add_js('jQuery(document).ready(function(){jQuery("#codeexamples-tabs").tabs();});', 'inline');
?>
<div id="codeexamples-tabs">
<?php
$node = menu_get_object();
if($node){
 $field = field_get_items('node', $node, 'field_codeexampleentityreference');
 if($field){
  $listtabs = '<ul>';
  $tabcontents = '';
  foreach ($field as $codeexampleentityreference)
  {
    $nid = $codeexampleentityreference['target_id'];
    $tabname = $nid;
    $codeexample = node_load($nid);
    $codeexample_output = node_view($codeexample);
    $field2 = field_get_items('node', $codeexample, 'field_language');
    if($field2){
     $tabname = $field2[0]["taxonomy_term"]->name;
    }
    $listtabs = $listtabs . '<li><a href="#codeexamples-tab-'.$nid.'">'.$tabname.'</a></li>';
    $tabcontents = $tabcontents . '<div id="codeexamples-tab-'.$nid.'">'.render($codeexample_output).'</div>';
   }
   $listtabs = $listtabs.'</ul>';
   print $listtabs;
   print $tabcontents;
  }
 }
?>
</div><!-- /.codeexamples-tabs -->

Leave a Reply

Your email address will not be published. Required fields are marked *