Posted October 3, 2019
I'm working on a website which has a list of products, displayed in a View. Each product has an "provider" who produces it, associated with the product content type by an entity reference field to a Provider content type and displayed in the view. The client wanted contact information for the providers to show up in the list as well.
It would have been a bit bulky and repetitive to have the contact information displaying in each row of the View. Therefore, I wanted to display a block above the results containing the contact information for only the provider selected in the "provider" exposed filter, but showing nothing if no provider was chosen. Here's how I did that.
First, I added an attachment display to the View, called it "Provider contact info" and attached it to the display with the list of products. I set the attachment to display 1 item, because otherwise it will display its content once for every row in the view—definitely not what we want.
The attachment and its parent display both have a relationship "field_provider: Content", which gives us access to fields from the Provider content type. I added the desired fields to the attachment (address, phone, email, etc), making sure to select the relationship in each field's configuration. We want to override the display for this attachment only, because it's displaying different fields to what's in the products list. This is also where you'll configure how you want your fields to display, rewrite them, etc, if needed.
Now we need to filter the attachment by the Provider exposed filter choice. This will make sure it displays the correct information for the selected provider, but nothing if none is chosen.
To do this, we add a contextual filter to the attachment, making sure we're adding it to this display only. We select the Provider (field_provider) option on our Product content type (or whatever your field/content type are called). Do not use a relationship. Under "When the filter value is not available" select the "Provide default value" option. In the Type dropdown, select "Query parameter". This is where we enter the value of our exposed filter. To find this, we go into the configuration for our "Provider" exposed filter. In the Filter Identifier field, we have the value "provider". This is the string that gets passed into the URL to identify this filter, to tell the View what to show. So in the contextual filter configuration, we put "provider" as the query parameter value (without the quotes). In this case, we don't add a fallback value, and it's a single value, not multiple, so we're done. Click "Apply (this display)", save your view, and voila: you should see...nothing, until you select an option from the exposed filter you used as the contextual filter for your attachment, and then you should see the correct data show up in your attachment.