Tuesday, 23 February 2016

Drupal 7 views : How to sort order on a Multiple data field.

The task - What we have is a column of Dates of when the entity was sent. This could be one or more dates, ie multivalued . The objective here is for each row to present the most recent sent date and for the rows to be sorted by the date. 
 I encountered 2 issues that I had to get over.  
If we we’re just to add a sort here then we get multiple returns for each Entity, which we don’t want. 
The second issue is that the date ‘Multiple Field Settings’ - ‘Reversed’ tick box doesn’t effect my result ordering in that field.  And therefore display the oldest date and not most recent. 
Let’s take a look at the first issue.  To resolve this what I like to do is group the fields together and present 1 row for each Entity , but by doing so the normal way through > Table > Settings > ‘Grouping field’  .  Here I get the right results in the right order but it creates multiple tables for each row.  The solution is to use the module ['https://www.drupal.org/project/views_table_rowspan'] Views Table Rowspan.  With this module you
  1. Install it
  2. Clone your View ‘display’ and this time set the ‘Format’ to ‘table rowspan’ 
  3. now in Table Rowspan > Settings .  Add all the fields and then tick ‘Merge rows in table’ 

Now with that second issue a full fix is to investigate and write a patch. Like https://www.drupal.org/node/2070313  

I’ll be taking a look at this shortly . In the meantime though it can be dealt with in the template layer ( as long as it’s not being outputted to CSV ) .  For my template fix I output all results with out any styling or HTML. Separated with ‘,’ - if the string passes has a comma then I split the value in to an array and take the last element as my date. 
Here's code I used in the template overwrite.

$html_wrapper = '%REPLACE%'; 

if (strpos($output, ',') != TRUE ){

  print str_replace('%REPLACE%', $output, $html_wrapper);


elseif(strpos($output, ',') == TRUE ) {

  $date_array = explode(',', $output);

  $last_date = end($date_array);

  print str_replace('%REPLACE%', $last_date, $html_wrapper) ;


else {

  print str_replace('%REPLACE%', $output, $html_wrapper);


No comments: