Filtering Entity Reference Values in Autocomplete Field in Drupal 7

Drupal is great. You can create just about any functionality without writing any code. You just download a module, right? “There’s a module for that” is the standard response to most Drupal questions. OK, which module? There are 6,877 actively maintained Drupal 7 modules at the time of writing. It can take a full day of creative, lateral-thinking Googling to find which module will do what you want and how to use it. Such was my plight this week trying to get an Autocomplete field to only offer user’s own content in when linking to other nodes through an Entity Reference field.

I’m not going to explain what the Entity Reference module is, I take that as a given. So I assume that you have Entity Reference and its dependencies installed and enabled.

Let’s say you have a content type Book and another content type Chapter. Within Book you want to be able to assemble the list of Chapter Entity References that are in a Book. Fine. You create a field, say, Chapters in your Book which is of type Entity Reference. If you select the Autocomplete widget type you can even drag and drop the order of chapters. Excellent. Now, say you only want to offer the author’s own chapters to be referenced in the book. Well, now we enter a whole new ballgame of complication.

Working on the principle that there’s a module for that, I just spent about 8 hours working out how to do this without writing a new module (and re-inventing the wheel). You need to start with the Views module. The Views module is a bit of a Swiss Army Knife. The name suggests that it creates displayable pages on your data that match certain criteria, etc. Well, yes, it does that. It also does other clever / more subtle stuff. In addition to creating a Page or a Block display, you can also create an Entity Reference display. This is the key to filtering the results of your Autocomplete field widget so that only the currently logged-in user’s content is offered to put in the field for the Book.

You create a new View, let’s say Reference Authors Chapters and create an Entity Reference display for it. Select Relationships/Add (hidden under Advanced) and select Content: Author. Now go over to Fields Criteria/Add and add User: Current and then ‘Yes’ to matching to the current logged-in user. You should also add another filter for the node type to select just the Chapter nodes. In Format/Format you need Entity Reference List and in Format/Format/Settings you need to select something like the Title for the search fields your Chapter. Now you can Save.

Finally you can go back to your Book content type and go to the Manage Fields section. Go to the Edit item for the Chapters field and Entity Selection and select the Mode to be Views: Filter by an entity reference view. Then select your view that you just created as the View used to select the entities.

Then you’re done.

Easy.

When you know how.