Drupal - Get a View's Export Code Programmatically from CTools

Category:

With Drupal and Views, we are able to configure a View's settings and import/export them across Drupal sites. This allows us to create backup copies of our View's settings and/or move a View between Drupal sites with relative ease.

Typically this is a manual process by using the Views UI to copy the "export" code string from one site:

http://dev.example.com/admin/structure/views/view/frontpage/export

..and then paste the string into the "import" form on another site:

http://www.example.com/admin/structure/views/import

This is a wonderful feature for Views (provided by CTools) and can be used to save back up copies of a View's settings in case of emergencies, or for moving a View from a development site to a live site.

If we get tired of doing this manually, the machines will be happy to help us with this task because we care for them too. To retrieve the "export" code string programmatically, we'll need to use two functions in our custom module:

$view = views_get_view('frontpage');
$export_code_string = views_export_view($view);

The $export_code_string will contain the export code we would normally find at the admin/structure/views/view/frontpage/export page. Be sure to replace 'frontpage' with the machine name of your View.

Now that we have the ctools export string for the View, we can do whatever we want with it.

For myself, the need for this functionality was inspired by the desire to create the Views Revisions module. The module will create revisions to track the changes to a View's settings over time. The revisions contain the ctools export data string for the View, which makes it possible to rollback to an older version of a View if ever need be.

In the past, I've used the manual approach to copy the export data of a View into a git repo and track the changes over time that way. It worked OK for being able to revert to an older version if necessary, but automating this tedious task was the inspiration for the module indeed. Enjoy!

Comments

Instead of ctools_export_load_object() to get the view, use views_get_view() which is a much simpler function to use.

Thank you for your input merlinofchaos! I'll be sure to use views_get_view() in the future, and I will update the Views Revisions module and this article with that code. https://drupal.org/node/2163915

I've updated the Views Revisions module to use views_get_view() instead of ctools_export_load_object() and have updated this article to reflect these changes. Thanks again merlinofchaos for making my life easier with Views!

Add new comment