Programatically Updating Views Permissions

Last updated on
1 December 2016

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

In the event that you wanted to change a single, or multiple views permissions en masse, you simply need to:

  1. Load the view with - $view = views_get_view([machine name])
  2. Set the display to the master (aka default) - $view->set_display('default');
  3. Set the desired permissions in the array "$view->display_handler->display->display_options['access']"

The code below can run in a node page, and will set the default to restrict views access to users that are logged in. You may need to clear caches after running in order for the settings to take effect.

Code 1: Node page that will accept a view machine name as argument, or default to setting all.

<?php
$a = arg();
if (isset($a[2])) {
  switch ($a[2]) {
    case 'all':
      $views = views_get_views_as_options();
    break;

    default:
      $views = array($a[2] => $a[2]);
    break;
  }
} else {
  echo "Usage: you must supply a views machine_name or all to process all views.";
  $views = array();
}
foreach ($views as $key => $label) {
  list($machine_name) = explode(":", $key);
  $view = views_get_view($machine_name);
  $view->set_display('default');
  dpm($view->display_handler->display->display_options['access'], " views_get_view($machine_name);");
  $view->display_handler->display->display_options['access']['type'] = 'perm';
  $view->display_handler->display->display_options['access']['perm'] = 'access content';
  $view->save();
  dpm($view->display_handler->display->display_options['access'], " after setting perms;");
  //break;
}

?>

Help improve this page

Page status: No known problems

You can: