Exporting Drupal Views to code

Ever been is a situation where you have a crazy complex View and realize you messed it up right AFTER you hit the save button? It's happened to all of us at one point or another. Having the ability to easily revert your View at anytime can be a life saver. This is why we always use the methods below when building larger Views. There are some other substantial benefits to keeping your Views in code. It allows you to commit to your version control system and makes deploying Views from a development environment to a production site a snap. Did I convince you yet? Ok enough yakin', let's get to it!

The following tutorial involves Drupal 7 and Views 3. It is virtually the same with Drupal 6 and Views 2 (and the one difference is noted).

If you don't already have a custom module created, now is the time to do it!

In your custom module (in my case it's called deckfifty.module) we are going to use the hook_views_api(). This simple hook tells Views that this module supports the Views API and what version of the API.

Note: If you are using Drupal 6 and Views 2 the "api" below should be 2.0

/**
 * Implements hook_views_api().
 */
function deckfifty_views_api() {
  return array('api' => 3.0);
}

Next, create a new file in the same directory as your custom module named deckfifty.views_default.inc

In the Views UI, find the View that want in code and click "export". Copy the exported View.

Back to the deckfifty.views_default.inc file - we'll use the hook_views_default_views(). This is where we will place our exported Views code.

/**
 * Implements hook_views_default_views().
 */
function deckfifty_views_default_views() {

// exported view goes here

$views[$view->name] = $view;

// return views
  return $views;
}

As you can probably guess, simply paste your exported Views code where commented.

Lastly, navigate to your Views advanced settings and clear your Views cache. This is allow Views to check for our newly created default views file.

That's it! Now you can "revert" to this state anytime. When Views is using the code you will see "In code" below your View name and when you edit and save the View this changes to "overriding code".

Now when you are ready to make your new changes the default setting for this View, simply export the View again and paste over the code in your hook_views_default_views().