WebMW
WebMW

Reputation: 524

D7: Grouping Content via Entity Reference fields

In a Views Unformatted List, is there a way to group nodes of the same content type together?

Example:

Each node in Content Type "Attendee" specifies an attendee for an upcoming event. Some of these attendees are "Friends" of another attendee, and in order to link them together, I used an Entity Reference field like so:

https://i.sstatic.net/6mWnx.png

Now in Views, how do I get these linked Friends to appear right after the attendee they are going with? (So the referencing "parent" entity is displayed first and any referenced "children" entities are displayed after?)

Formatting example:

Say we have Bob, Bill, & Tom... Bill is the only one with friends attending; these two friend's names are Hansel & Gretel.

Hansel & Gretel would then both have Bill selected in their Entity Reference field and the output should show:

The "Views Field View" module will not work for my case because I am actually using the "Views PDF" module which is not currently compatible together. Views PDF still allows me to use relationships though and I'm hoping this is still possible-- even if I have to code custom theming information or something.

Upvotes: 0

Views: 317

Answers (1)

Billy
Billy

Reputation: 35

You can override the sorting for a view via the views_query_alter hook.

Create a custom module, and add this code to your_module.module file:

<?php

/**
 * Implements hook_views_query_alter()
 */
function YOUR_MODULE_views_query_alter(&$view, &$query) {
  if ($view->name == 'YOUR_VIEW_NAME') {
    $query->orderby = array(
      array(
        'field' => 'COALESCE(ATTENDING_WITH_TITLE_FIELD, FRIEND_TITLE_FIELD)',
        'direction' => 'DESC',
      ),
       array(
        'field' => '(ATTENDING_WITH_TITLE_FIELD = FRIEND_TITLE_FIELD)',
        'direction' => 'ASC',
      )     
    );
  }
}

The first order by will sort by the name of the friend they're attending with, or their own name if this isn't available (null).

The second part will make sure that friends who have friends with them appear first.

Kudos: http://blog.blenderbox.com/2011/11/03/how-to-modify-a-drupal-7-view-query-to-order-by-two-columns-simultaneously/

Upvotes: 0

Related Questions