Drupal - Get a View's Export Code Programmatically from CTools
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:
..and then paste the string into the "import" form on another site:
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!