0

How can I check from a custom module if a specific view is enabled or disabled?

3 Answers 3

1

Having a view object, checking if the view is disabled just requires to check the value of $view->disabled; if it is TRUE, the view is disabled.

if (!$view->disabled) {
  // The view is enabled.
}

This method works independently from the view type, and it doesn't give false negatives when a module alters the output returned from a hook implemented by another module, which is what could happen with hook_block_view(), whose output could be altered by hook_block_view_alter().

To get a view object, you can use views_get_view($name), which is the function used also from views_block_view().

if ($view = views_get_view($name)) {
  if ($view->access($display_id)) {
    $view->set_display($display_id);
    if (isset($view->display_handler)) {
      $output = $view->display_handler->view_special_blocks($type);
      // Before returning the block output, convert it to a renderable
      // array with contextual links.
      views_add_block_contextual_links($output, $view, $display_id, 'special_block_' . $type);
      $view->destroy();
      return $output;
    }
  }
  $view->destroy();
}

If you also need to know if the currently logged-in user has access to the view (i.e. the user can see the view output), you need also to call $view->access($display_id), where $display_id can be easily get from the delta of the block with list($nothing, $type, $name, $display_id) = explode('-', $delta);.

The code you need to use, in the case of just checking if the view is enabled is similar to the following.

$view = views_get_view($name);
// Always check the value returned from views_get_view(), since it can return NULL.
if (!empty($view) && $view->disabled) {
  // The view exists and it is enabled.
}

In the case you need to check the currently logged-in user has access to the view, the code should be similar to the following one.

$view = views_get_view($name);
// Always check the value returned from views_get_view(), since it can return NULL.
if (!empty($view) && $view->access($display_id)) {
  // The view exists and the user has access to it.
}
1

I did it with module_invoke().

$block = module_invoke('views','block_view','-exp-machinenameoftheview-page');
if (!empty($block)) {
  // The view is enabled.
}
else{
  // The view is disabled.
}
1

You can use the views_get_view function to do this.

$view = views_get_view('view_name');
if ($view->disabled) {
  // Do something
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.