Revert and disable a view programmatically

Public

I know that such a snippet has already been submitted, here is an improved version.

May be useful when you would like to clone a view to be able to deploy it through Features (when a view has been provided by code in a module, we can't add it to a Feature).

Drupal Commerce provide several views and I had to override them and deploy through Features, I use this function when I replace a view provided by Commerce.

</> CopyGet raw version
php
  1. /**
  2.  * Revert to default, then disable a given list of views.
  3.  *
  4.  * @param $view_name array Array of machine names of the views to revert
  5.  */
  6. function store_common_revert_and_disable_views($view_names) {
  7. $changed = FALSE;
  8. $views_status = variable_get('views_defaults', array());
  9.  
  10. foreach ($view_names as $view_name) {
  11. // Revert the view
  12. $view = views_get_view($view_name);
  13. if ($view->type == t('Overridden')) {
  14. // Revert the view.
  15. $view->delete();
  16. // Clear its cache.
  17. ctools_include('object-cache');
  18. ctools_object_cache_clear('view', $view->name);
  19. }
  20.  
  21. // Disable the view
  22. if ($views_status[$view_name] !== TRUE) {
  23. $views_status[$view_name] = TRUE;
  24. $changed = TRUE;
  25. }
  26. }
  27.  
  28. // If we made changes to views status, save them and clear caches
  29. if ($changed) {
  30. variable_set('views_defaults', $views_status);
  31. views_invalidate_cache();
  32. }
  33. }