Drupal Developer Tip: Embed View

Submitted by Daniel Henry on 05/08/2013 - 11:34:am

I regularly find myself in need of this handy code snippet. One of our clients wanted to create page that had a list of services available in a given country. My first thought is to just use a view with a contextual filter and call it a day. But the list was not the only content on the page. Their was a title and description that they wanted to be able to easily edit, they wanted control over the url, the metadata, and it was multilingual to boot. Views just wasn’t offering the necessary control the customer needed. So instead we simply created a normal node for them with a few add ons like the core alies system, taxonomy category to select the country, and meta tags module to set the meta title and description. Unknown to the custom an additional hidden field was added to store the view information. On save the view and display are attached based on the taxonomy terms selected. Then on view the following code displays the list:

  1. $viewName = 'country_services';
  2. $display_id = 'block_1';
  3. $myArgs = array($language, $country);
  4. $node->content['field_view_embed'] = views_embed_view($viewName, $display_id, $myArgs);

 

Now you have a dynamic query that can be edited through the expected user interface and an easy way for a customer to attach the desired info. Nice thing about this snippet is it works in Drupal 6 and 7 both.

 

Blog phot provided by Alexflx54