Using a View as a Content Field in Drupal

,

Sometimes in Drupal you’d like a field that pulls data from other fields, possibly other content types or who knows. If it’s relatively simple, you can use the Computed Field module to pull data straight from the database. But if you want to get really tricky, you can use the Node Reference Views module. For example, let’s say you want to include the weights of individual components of an item, so you get a dropdown list of components to choose from, then once you’ve chosen them, they will be displayed in your field formatted as you’ve selected in your View. In other words, imagine that you’re formatting a list of components using Views as you might normally do, but now you insert that in your node as a field.

So in short you use Node Reference to set the source of the data and you use Node Reference Views to set the format of the data.

Enable both modules.

Now, add a new field to your content type. You’ll have three choices – checkboxes, select list or auto-complete. It doesn’t really make any difference. This is just how you’re going to choose which ones to include. Select list works well for a medium number of choices %raisedbyturtles.orgexample the total number of components you’ll have available). On the next screen where you’re configuring the field, choose which content types are going to be available. In our case we have a special content type for components.

Choose your content types

Now we have to create view using the same name as the field type. If you have forgotten what you called it, raisedbyturtles.orgink to get the field name (you can also edit the field and it will tell you on the edit screen).

Hovering over link to get field name
This field name must be your view name as well (click to enlarge)

Now go over to the Views listing and create a new view and give it the same name as the field. In this case nr_component_weights. The view in this case is simple — we just grab the name of the component and the weight. We format it as fields (inline) and rows.

Views settings screen
Views Settings (click to enlarge)

Then, here’s the magic — under Display fields (as opposed to Manage fields) you can choose View as the display mode. The field will now automatically use the View that has the same name.

Display fields screenshot
Choose the View display formatter

Now when you go to your node edit screen, you can select whichever nodes (in this case Components) you want to include.

Screenshot: Node selection on edit screen
Select the nodes you want included in the view

Then when you view your page, it will include a field that consists of those nodes, formatted by the View you just created.

screenshot: as shown to end user
Voila - views output as a field

Magic!

Comments are closed.