Sunday 28 October 2012

Change display based on vocabulary using views, Drupal 7

Let's say we have two vocabularies called A and B.
Now I would like to display nodes with terms from vocabulary A as teasers and for vocabulary B I would like to change display to table.

This is how it can be done.

Clone Taxonomy Term view and give it a new name.
Change format to table and add your fields.

Configure contextual filter: Content: Has taxonomy term ID (with depth)
In section called:
When the filter value IS in the URL or a default is provided
Specify validation criteria
Validator: PHP code, and paste below

$tid = $argument;
$vid = db_query("SELECT vid FROM {taxonomy_term_data} WHERE tid = :tid", array(':tid' => $tid))->fetchField();

// replace with your own $vid (vocabulary id) values
if ($vid == 1) { 

$view->display_handler->set_option('style_plugin', 'default');
$view->display_handler->set_option('row_plugin', 'node');

}
return TRUE;



Your view now for vocabulary with id 1 (vocabulary A) will display data as node teasers and for rest it will be table.

It can be done the other way around, but it slightly more tricky as you need to add fields for table format and then change it back to content format.

$tid = $argument;
$vid = db_query("SELECT vid FROM {taxonomy_term_data} WHERE tid = :tid", array(':tid' => $tid))->fetchField();
// replace with your own $vid (vocabulary id) values
if ($vid == 2) { 

$view->display_handler->set_option('style_plugin', 'table');

//export view to get style plugin names and other info
  $view->display_handler->set_option('style_options', array(
  'grouping' => '',
  'override' => 1,
  'sticky' => 0,
  'order' => 'desc',
  'columns' => array(
    'field_group_picture' => 'field_group_picture',
    'title' => 'title',
    'field_informations' => 'title',
  ),
  'info' => array(
    'field_group_picture' => array(
      'separator' => '',
    ),
    'title' => array(
      'sortable' => 0,
      'separator' => '<br />',
    ),
    'field_informations' => array(
      'sortable' => 0,
      'separator' => '<br />',
    ),
  ),
  'default' => '-1',
)
);
}
return TRUE;

No comments:

Post a Comment