custom_formatter.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. Creating a Custom Formatter
  2. ===========================
  3. The third component of a field is the formatter. Thus far we have introduced how to create a field class and a widget class for a field. The field class is responsible for describing the field, loading data into it, and providing search support. The widget class provided a Drupal form for online editing of the field. Finally, the formatter is responsible for display of the field on a Tripal site.
  4. .. note::
  5. This guide assumes you already have your formatter class file created. For more information, see :doc:`manual_field_creation` or, :doc:`tripal_field_generator`.
  6. The formatter class is the simplest of all the Tripal field classes. Here we will again use the **obi__organism** field that comes with the ``tripal_chado`` module.
  7. The view() function.
  8. ~~~~~~~~~~~~~~~~~~~~
  9. In most cases the only function you need to implement is the ``view()`` function. This function is called whenever your field needs to be displayed on a page. The following code is from the ``obi__organism_formatter.inc`` class file.
  10. .. code-block:: php
  11. :linenos:
  12. public function view(&$element, $entity_type, $entity, $langcode, $items, $display) {
  13. if ($items[0]['value']) {
  14. $content = $items[0]['value']['rdfs:label'];
  15. if (array_key_exists('entity', $items[0]['value'])) {
  16. list($entity_type, $entity_id) = explode(':', $items[0]['value']['entity']);
  17. $content = l(strip_tags($items[0]['value']['rdfs:label']), 'bio_data/' . $entity_id);
  18. }
  19. // The cardinality of this field is 1 so we don't have to
  20. // iterate through the items array, as there will never be more than 1.
  21. $element[0] = array(
  22. '#type' => 'markup',
  23. '#markup' => $content,
  24. );
  25. }
  26. }
  27. In the code above the input arguments have the following meaning:
  28. - ``$element`` is the first argument. It is an array into which you should set the contents to be displayed.
  29. - ``$entity_type`` will always have the value ``Tripal Entity``.
  30. - ``$entity`` is the entity object which contains all information about the entity including the loaded data values.
  31. - ``$langcode`` is the language. This is used by Drupal to provide translations of data into other spoken languages. By default, Tripal does not use a language, as biological data is generally language agnostic. Consider for example a gene sequence or a feature coordinate.
  32. - ``$items`` is an array containing all of the loaded data for this field.
  33. - ``$display`` is the name of the display such as full page, a teaser, etc. Currently, Tripal does not distinguish between displays.
  34. The purpose of the ``view()`` function is to iterate through the values in the ``$items`` array, and format them into an appropriate display for viewing. Here you must remember the structure of the data in the ``$items`` array.
  35. To demonstrate this function, let's look at what we expect in our ``$items`` array. Using the `Citrus sinesis` organism from the User's Guide. We would expect an items array to look like the following:
  36. .. code::
  37. $items = [
  38. 0 => [
  39. "value" => [
  40. "rdfs:label" => "Citrus sinensis",
  41. "rdfs:type" => "Organism",
  42. "local:abbreviation" => "C. sinensis",
  43. "TAXRANK:0000005" => "Citrus",
  44. "TAXRANK:0000006" => "sinensis",
  45. "entity" => "TripalEntity:3",
  46. ],
  47. "chado-feature__organism_id" => 12,
  48. ],
  49. ];
  50. You may recall that the ``$items`` array structure is the same as that created by the ``load()`` function described in the :doc:`manual_field_creation` page. Note that each key in the ``value`` array is an accession for a controlled vocabulary term. These accessions are used to unambiguously describe the value. To display the organism on a page we need the element named ``rdfs:label``. Thus, we set the ``$content`` variable to contain this value as shown on line 4 of the ``view()`` function above.
  51. Because our organisms are also published entities we want to link to their respective pages each time an organism is displayed. Because the ``value`` array has an element named ``entity`` we know that this item is published. Lines 5-6 of the ``view()`` function shown above use this information to create a clickable link to the organism page. Finally, the ``$element`` argument is set to provide content of type ``markup``. This ``$element`` array is a `Drupal renderable array <https://www.drupal.org/docs/7/api/render-arrays/render-arrays-overview>`_.
  52. Lastly, notice the element named ``chado-feature__organsim_id``. This element is at the same level as the ``value`` element. This data is meant to be used internally by the field. It maps this fields values to the appropriate table in Chado where the data is stored.
  53. .. warning::
  54. You should never show the user any data that is outside of ``value`` element. Remember that your field can be shown by other viewers, including web services. By ensuring that data in the ``value`` element is mean to be displayed we ensure that information on the web page, web services, or any othe future form of display is always consistent.
  55. In summary, the following should be observed when processing the ``$items`` array for viewing:
  56. - A field with only one value (a cardinality of 1) will always have only one element in the ``$items`` array and can use the index 0. This is what has been done in this example code.
  57. - A field with more than one value can have any number of elements in the ``$items`` array. You should therefore iterate through all of them.
  58. - For every index in ``$item`` you should create a matching index in ``$element`` to display the data found in that ``$item``.
  59. - If there are no items, then nothing you return will be displayed.
  60. - For each element in the ``$items`` array there is a ``value`` key. Only the data in the ``value`` key should be shown to the user.
  61. - Each element in the ``$items`` array may have more than a ``value`` key. These values are meant to help manage the data.
  62. .. warning::
  63. You should never have SQL statments or any API calls that retreive data in the foramter ``view()`` function. The formatter should strictly format data for viewing.
  64. Creating Pagers
  65. ~~~~~~~~~~~~~~~
  66. The example shown in the previous section was for a field that will always only contain a single element. However some fields may contain a large number of elements. Consider an mRNA and it's relationships to subfeatures: exons, 5' UTRs, 3'UTRs, CDS, etc.). A large mRNA can have many relationships. Alternatively, consider the case where a genentic map content type may have a field that lists all of the markers on the map. Such a list could become extremely long on the page. In these cases it may be best to only list a few items at a time and to provide a pager to let the user cycle through the items. An example of a pager added to the bottom of relationships is shown in the example below.
  67. .. image:: custom_formatter.pager.1.png
  68. To create a pager we first need to calculate the number of items we want to display per page and the total number of pages required to display all of the data.
  69. .. code-block:: php
  70. $items_per_page = 10;
  71. $total_records = count($items);
  72. $total_pages = (int) ($total_records / $items_per_page) + 1;
  73. Next, we must initialize the pager by calling the ``pager_default_initialize`` function. We pass it the total number of records, the number of items per page and the index (i.e. ``$pelement``) for this pager on the page.
  74. .. code-block:: php
  75. $pelement = 0;
  76. $current_page = pager_default_initialize($total_records, $items_per_page, $pelement);
  77. The call to ``pager_default_initialize`` will return the current page. The current page is a numeric number indicating which page the pager is currently showing. The first time the page is loaded this will always be the first page. Each time the user navigates to other pages by clicking the "next" link or the numeric links then this ``view()`` function is called and the current page is set to the page being viewed. Next, we must theme the pager so that it follows the look-and-feel prescribed for the site. For this we use the Drupal ``theme()`` function.
  78. .. code-block:: php
  79. $pager = theme('pager', array(
  80. 'tags' => array(),
  81. 'element' => $pelement,
  82. 'parameters' => array(),
  83. 'quantity' => $total_pages,
  84. ));
  85. By default, all links in the pager cause the page to reload. We do not want the page to reload, rather we only want to update the contents of the field. The TripalFieldFormatter class provides a function named ``ajaxifyPager`` to convert a pager into an AJAX pager:
  86. .. code-block:: php
  87. $pager = $this->ajaxifyPager($pager, $entity);
  88. Now that we have a pager, it has been setup for AJAX and we know the current page that the user is viewing we can now display only the items from the ``$items`` array that are appropriate for the page being viewed. A common way to provide multiple items on a page is within a table. When we set the ``$element`` array we need to be sure to provide both the content and the pager:
  89. .. code-block:: php
  90. $element[0] = array(
  91. '#type' => 'markup',
  92. '#markup' => $content . $pager,
  93. );
  94. The settingsForm() Funtion.
  95. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  96. Sometimes you may want to provide some control to the site developer for the formatter. For example, the ``sbo__relationship_formater`` allows the site developer to customize the title that appears above the table that houses relationships and the text the appears if there are no relationships. By default the title is "Relationships" and the empty text indicates there are no relationships. Both are a bit too generic. The ``settingsForm()`` function allows you to provide a Drupal form for the field that appears on the **Administer > Strucutre > Tripal Content Types** on any content type's **manage display** page:
  97. .. image:: custom_formatter.settings.1.png
  98. The form shown in the screenshot above is provided by the ``settingsForm()`` function. The following code generates this form:
  99. .. code-block:: php
  100. :linenos:
  101. public function settingsForm($view_mode, $form, &$form_state) {
  102. $display = $this->instance['display'][$view_mode];
  103. $settings = $display['settings'];
  104. $element = array();
  105. $element['title'] = array(
  106. '#type' => 'textfield',
  107. '#title' => 'Table Header',
  108. '#default_value' => array_key_exists('title', $settings) ? $settings['title'] : 'Relationship',
  109. );
  110. $element['empty'] = array(
  111. '#type' => 'textfield',
  112. '#title' => 'Empty text',
  113. '#default_value' => array_key_exists('empty', $settings) ? $settings['empty'] : 'There are no relationships',
  114. );
  115. return $element;
  116. }
  117. The form is typical of any form. Note, however that the ``#default_value`` is set using the current settings values.
  118. A settings form is useful but it only works when Drupal knows what settings you want for your field. You must provide the settings names (e.g. "title" and "empty" in this case) when you attach your field to a given content type (i.e. bundle). You tell Drupal to attach this field to a content type using the ``hook_bundle_instance_info`` function. See
  119. the :doc:`create_instance` to learn more about this function. Briefly, the ``display`` section of the info array for the ``sbo__relationship`` field contains the following settings for the ``display``:
  120. .. code-block:: php
  121. 'display' => array(
  122. 'default' => array(
  123. 'label' => 'hidden',
  124. 'type' => 'sbo__relationship_formatter',
  125. 'settings' => array(
  126. 'title' => 'Relationships',
  127. 'empty' => 'There are no relationships'
  128. ),
  129. ),
  130. ),
  131. .. warning::
  132. In order for the ``settingsForm()`` implemented to be available on the "Manage Display" page, you must also implement ``settingsSummary()`` as described below.
  133. The settingsSummary() Function.
  134. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  135. The ``settingsSummary()`` function provides a summary of the current settings values for a field on the **manage display** page. The following shows the same relationship field from the previous section, but with the settings form closed, and a summary of the current values shown:
  136. .. image:: custom_formatter.settings.2.png
  137. An example of the ``settingsSummary()`` function that generates the summary in the image above is as follows:
  138. .. code-block:: php
  139. :linenos:
  140. public function settingsSummary($view_mode) {
  141. $display = $this->instance['display'][$view_mode];
  142. $settings = $display['settings'];
  143. $summary = t('Title: @title<br>Empty: @empty',
  144. array(
  145. '@title' => $settings['title'],
  146. '@empty' => $settings['empty'])
  147. );
  148. return $summary;
  149. }