How to list all views and then append a header to each one

Not applicable

Hello,

I need to change the header text for all Smartdocs based views once. The following code would be added to some custom module and then removed after the desired result is achieved.

  $all_views = views_get_all_views(); 
  foreach ($all_views as $view) {
    if ($view->tag == 'smartdocs') {
      /* Header: Global: Text area */
      $options = array(
        'id' => 'area',
        'table' => 'views',
        'field' => 'area',
        'label' => 'My Header',
        'format' => 'full_html',
        'tokenize' => TRUE,
      );

//This is called a heredoc string
$options['content'] = <<<EOT
<style>
table {
  margin-bottom: 10px; 
  background-color: #D6EFF9; 
  color: #1472D1; 
  border-radius: 5px;
}
td {
  padding: 10px 10px 10px 10px; 
}
</style>
<div>
<table>
  <tbody>
    <tr><td>Magic Number</td><td>[field_magic_number]</td></tr>
    <tr><td>Product(s)</td><td>[field_api_products]</td></tr>
  </tbody>
</table>
</div>
EOT;

      $view->display_handler->set_option('header', array('text' => $options));
    }//end if
  }//End foreach view

However the display handler is set to NULL, so I cannot use the correct function to change and update the view. How do I correctly set the display handler and save my changes to all the views?

Next part of the question: This change needs to be applied to all future smartdocs views as well. What hook should I use to run the following code when a view is created?

//Run this code snippet when a view is created

if ($view->tag == 'smartdocs') {
  /* Header: Global: Text area */
  $options = array(
  'id' => 'area',
    'table' => 'views',
    'field' => 'area',
    'label' => 'My Header',
    'format' => 'full_html',
    'tokenize' => TRUE,
  );

//This is called a heredoc string
$options['content'] = <<<EOT
<style>
table {
  margin-bottom: 10px; 
  background-color: #D6EFF9; 
  color: #1472D1; 
  border-radius: 5px;
}
td {
  padding: 10px 10px 10px 10px; 
}
</style>
<div>
<table>
  <tbody>
    <tr><td>Magic Number</td><td>[field_magic_number]</td></tr>
    <tr><td>Product(s)</td><td>[field_api_products]</td></tr>
  </tbody>
</table>
</div>
EOT;

  $view->display_handler->set_option('header', array('text' => $options));
}//end if

Would these hooks work?

hook_views_pre_view
hook_views_pre_build
hook_views_post_build
hook_views_pre_execute
hook_views_post_execute
hook_views_pre_render
hook_views_post_render

Thank you for your time,

Mitchel

Solved Solved
0 4 462
1 ACCEPTED SOLUTION

Not applicable
<?php

/* BACKUP CONFIGURATION (DATABASE) BEFORE EXECUTING THIS CODE - CHANGES TO VIEWS ARE PERMANENT */

/**
 * Implements hook_menu().
 * Adds a new menu option to the admin bar, use to update all smartdocs views
 */
function my_module_menu() {
  $items = array();

  //Add a my_module menu to the admin toolbar
  $items['admin/my_module'] = array(
    'title' => 'my_module',
    'description' => 'my_module custom menus',
    'access arguments' => array('administer site configuration'), //If user can admin site then allow access
  );
  
  $items['admin/my_module/rebuild_views'] = array(
    'title' => 'rebuild views',
    'description' => 'Adds Global:Text Area to header text for all smartdocs derived views.',
    'page callback' => '_my_module_rebuild_smartdocs_views',
    'access arguments' => array('administer views'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}


/**
 * Implements hook_views_pre_view
 * Adds Global:Text Area to header text for smartdocs derived views
 * This code runs anytime a view is accessed
 */
function my_module_views_pre_view(&$view, &$display_id, &$args){
  //Check if view is a Smartdoc derived view
  if ($view->tag == 'smartdocs') {
    _rebuild_view($view);
  }//end if
}

/**
 * Custom function to rebuild all views
 * Adds Global:Text Area to header text for all smartdocs derived views
 */
function _my_module_rebuild_smartdocs_views(){
  $count = 0;//Count the number of views affected
  $output = "<table><tr><th>Order</th><th>Name</th></tr>";//HTML rendering a table listed the changed views
  
  //Get all views and loop through each one
  $all_views = views_get_all_views();
  foreach ($all_views as $view) {

    //Check if view is a Smartdoc derived view
    if ($view->tag == 'smartdocs') {
      _rebuild_view($view);
      $output .= "<tr><td>" . ++$count . "</td><td>" . $view->name . "</td></tr>";
    }//end if
  }//End foreach view
  
  //Close the table
  $output .= "</table>";   
  
  //Check changes if Devel module is installed and enabled
  custom_dpm($all_views);
  
  return $output;
}

/**
 * Custom helper function to set header text in desired views
 * Header text references Products and magic number
 */
function _rebuild_view(&$view){
  //Initialize the display handler
  $view->set_display();

  //Setup the global text header
  $options = array(
    'id' => 'area',
    'table' => 'views',
    'field' => 'area',
    'label' => 'Custom Label',
    'format' => 'full_html', //"Global: Text Area" type
    'tokenize' => TRUE, //Set to true so tokens evaluate to referenced values
  );
      
//PHP heredoc string for the content of the header
$options['content'] = <<<EOT
<style>
table {
/* Custom CSS */
}
</style>
<div>
<table>
  <tbody>
    <tr><td>  Magic Number </td><td> [field_magic_number]  </td></tr>
    <tr><td>  Product(s) </td><td> [field_api_products]  </td></tr>
  </tbody>
</table>
</div>
EOT;

  //Set the header Global: Text Area
  //This overwrites all header text
  $view->display_handler->set_option('header', array('text' => $options));
  
  /* OPTIONS - POPULATE WITH THE DESIRED VIEWS SETTINGS 
   * USE views_db_object::get_items($type, $display_id = NULL) ON A CUSTOM VIEW TO GET CODE */
  $options = array();
  
  //incomplete example - Set field_api_products and append to view
  $options = array(
    'id' => 'field_api_products',
    'table' => 'field_data_field_api_products',
    'field' => 'field_api_products',
    'relationship' => 'reverse_field_api_model_node',
    'group_type' => 'group',
    'exclude' => 1,
    'alter' => array(
      'alter_text' => 0,
      'make_link' => 0,
      'absolute' => 0,
      'external' => 0,
      'replace_spaces' => 0,
      'path_case' => 'none',
      'trim_whitespace' => 0,
      'nl2br' => 0,
      'word_boundary' => 1,
      'ellipsis' => 1,
      'more_link' => 0,
      'strip_tags' => 0,
      'trim' => 0,
      'html' => 0,
    ),
    'element_default_classes' => 1,
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'click_sort_column' => 'value',
    'type' => 'text_default',
    'settings' => array(),
    'group_column' => 'value',
    'group_columns' => array(),
    'group_rows' => 1,
    'delta_limit' => 'all',
    'delta_offset' => 0,
    'multi_type' => 'separator',
    'separator' => ',',
    'field_api_classes' => 0,
  );
  
  $item_types = array(
    'field' => 'field', 
    'argument' => 'argument', 
    'sort' => 'sort',
    'filter' => 'filter',
    'relationship' => 'relationship',
    'header' => 'header',
    'footer' => 'footer',
    'empty' => 'empty', //No results
  );
  $view->add_item($view->current_display, $item_types['relationship'], $options['table'], $options['field'], $options, $options['id']);

  //Save changes and clear all views cache
  views_save_view($view);
}

/**
 * Custom debugging function
 */
function custom_dpm(&$input, $name = NULL, $type = 'status'){
  if (module_exists('devel')) {
    dpm($input, $name, $type);
  }
}

View solution in original post

4 REPLIES 4

Not applicable
//Initialize the display handler
$view->set_display();
//Save changes
views_save_view($view);

Not applicable
//Clear the cache for the view using the cache plugin
$view->display_handler->get_plugin('cache')->cache_flush();

//alternative method
cache_clear_all($view->name . ':', 'cache_views_data', TRUE);

Clearing the cache is unnecessary after using views_save_view(). Referencing

https://api.drupal.org/api/views/includes!view.inc/function/view%3A%3Asave/7.x-3.x and

https://api.drupal.org/api/views/views.module/function/views_invalidate_cache/7.x-3.x

The cache for all views is cleared each time a view is saved using this method.

Not applicable
<?php

/* BACKUP CONFIGURATION (DATABASE) BEFORE EXECUTING THIS CODE - CHANGES TO VIEWS ARE PERMANENT */

/**
 * Implements hook_menu().
 * Adds a new menu option to the admin bar, use to update all smartdocs views
 */
function my_module_menu() {
  $items = array();

  //Add a my_module menu to the admin toolbar
  $items['admin/my_module'] = array(
    'title' => 'my_module',
    'description' => 'my_module custom menus',
    'access arguments' => array('administer site configuration'), //If user can admin site then allow access
  );
  
  $items['admin/my_module/rebuild_views'] = array(
    'title' => 'rebuild views',
    'description' => 'Adds Global:Text Area to header text for all smartdocs derived views.',
    'page callback' => '_my_module_rebuild_smartdocs_views',
    'access arguments' => array('administer views'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}


/**
 * Implements hook_views_pre_view
 * Adds Global:Text Area to header text for smartdocs derived views
 * This code runs anytime a view is accessed
 */
function my_module_views_pre_view(&$view, &$display_id, &$args){
  //Check if view is a Smartdoc derived view
  if ($view->tag == 'smartdocs') {
    _rebuild_view($view);
  }//end if
}

/**
 * Custom function to rebuild all views
 * Adds Global:Text Area to header text for all smartdocs derived views
 */
function _my_module_rebuild_smartdocs_views(){
  $count = 0;//Count the number of views affected
  $output = "<table><tr><th>Order</th><th>Name</th></tr>";//HTML rendering a table listed the changed views
  
  //Get all views and loop through each one
  $all_views = views_get_all_views();
  foreach ($all_views as $view) {

    //Check if view is a Smartdoc derived view
    if ($view->tag == 'smartdocs') {
      _rebuild_view($view);
      $output .= "<tr><td>" . ++$count . "</td><td>" . $view->name . "</td></tr>";
    }//end if
  }//End foreach view
  
  //Close the table
  $output .= "</table>";   
  
  //Check changes if Devel module is installed and enabled
  custom_dpm($all_views);
  
  return $output;
}

/**
 * Custom helper function to set header text in desired views
 * Header text references Products and magic number
 */
function _rebuild_view(&$view){
  //Initialize the display handler
  $view->set_display();

  //Setup the global text header
  $options = array(
    'id' => 'area',
    'table' => 'views',
    'field' => 'area',
    'label' => 'Custom Label',
    'format' => 'full_html', //"Global: Text Area" type
    'tokenize' => TRUE, //Set to true so tokens evaluate to referenced values
  );
      
//PHP heredoc string for the content of the header
$options['content'] = <<<EOT
<style>
table {
/* Custom CSS */
}
</style>
<div>
<table>
  <tbody>
    <tr><td>  Magic Number </td><td> [field_magic_number]  </td></tr>
    <tr><td>  Product(s) </td><td> [field_api_products]  </td></tr>
  </tbody>
</table>
</div>
EOT;

  //Set the header Global: Text Area
  //This overwrites all header text
  $view->display_handler->set_option('header', array('text' => $options));
  
  /* OPTIONS - POPULATE WITH THE DESIRED VIEWS SETTINGS 
   * USE views_db_object::get_items($type, $display_id = NULL) ON A CUSTOM VIEW TO GET CODE */
  $options = array();
  
  //incomplete example - Set field_api_products and append to view
  $options = array(
    'id' => 'field_api_products',
    'table' => 'field_data_field_api_products',
    'field' => 'field_api_products',
    'relationship' => 'reverse_field_api_model_node',
    'group_type' => 'group',
    'exclude' => 1,
    'alter' => array(
      'alter_text' => 0,
      'make_link' => 0,
      'absolute' => 0,
      'external' => 0,
      'replace_spaces' => 0,
      'path_case' => 'none',
      'trim_whitespace' => 0,
      'nl2br' => 0,
      'word_boundary' => 1,
      'ellipsis' => 1,
      'more_link' => 0,
      'strip_tags' => 0,
      'trim' => 0,
      'html' => 0,
    ),
    'element_default_classes' => 1,
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'click_sort_column' => 'value',
    'type' => 'text_default',
    'settings' => array(),
    'group_column' => 'value',
    'group_columns' => array(),
    'group_rows' => 1,
    'delta_limit' => 'all',
    'delta_offset' => 0,
    'multi_type' => 'separator',
    'separator' => ',',
    'field_api_classes' => 0,
  );
  
  $item_types = array(
    'field' => 'field', 
    'argument' => 'argument', 
    'sort' => 'sort',
    'filter' => 'filter',
    'relationship' => 'relationship',
    'header' => 'header',
    'footer' => 'footer',
    'empty' => 'empty', //No results
  );
  $view->add_item($view->current_display, $item_types['relationship'], $options['table'], $options['field'], $options, $options['id']);

  //Save changes and clear all views cache
  views_save_view($view);
}

/**
 * Custom debugging function
 */
function custom_dpm(&$input, $name = NULL, $type = 'status'){
  if (module_exists('devel')) {
    dpm($input, $name, $type);
  }
}