“This is the real secret of life -- to be completely engaged with what you are doing in the here and now. And instead of calling it work, realize it is play.” ― Alan Watts

Order a view by an entity reference field on a node - 8

March 5, 2020

Imagine you have a content type on your site called Article and you have another content type called Author.

The Article content type has an entity reference field which can reference an Author - essentially a way to say this article was written by this author.

Next your client asks you for a page listing all the articles but they want a way for the user to sort the listing based on certain parameters, one of which is the author.

If you try to just order by the author field on a view that is displaying articles then it will order by the target_id of the author, since that is what is stored on the article entity.

You can confirm this by turning on Show SQL query in your views module config settings then going back to your article view settings and using the sort on the actual view preview.

So we need to tell the view to use the title of the referenced author (Assuming your author content type uses the title field for the name of the author). The solution is to create a relationship on your view using the entity reference field for the author.

Don't require this relationship, just provide it so it can be used.

step 1

And then add a new sort criteria using the title field, but make sure you use the relationship so that the sort function is always using the title from the referenced author and not from the article or anywhere else.

step 2

And there you go...Any issues post a comment below!