Hi, I just created some Views and Rules in Drupal 7, then I export them using Rules and Views UI and save them into text files. I need them to be created automatically on my module installation so I don't need to import them manually. Is there any function I can use to import them programmatically?

Comments

schnippy’s picture

Sure - the views part is fairly straight forward. You want to start by exporting the view you want to add to your module. Then in your module you need the following two functions:

/**
 * Implements hook_views_api().
 */
function YOURMODULE_views_api() {
  list($module, $api) = func_get_args();
  if ($module == "views" && $api == "views_default") {
    return array("version" => "3.0");
  }
}

/** 
 * Implementation of hook_views_default_views().
 */
function YOURMODULE_views_default_views() {

  $export = array();

   < YOUR VIEW IMPORT CODE HERE >

  $export['test'] = $view;
  return $export;

}

I've got a module that loads multiple views so I drop them all into one directory as simple text files and then load each one with a function like this:

/** 
 * Implementation of hook_views_default_views().
 */
function YOURMODULE_views_default_views() {

  foreach (glob(dirname(__FILE__) . "/views/*.inc") as $filename) {
    include_once($filename);
    $views[$view->name] = $view;
  }
  return $views;
}

Of course another way to do this (or figure out how to do any of the other exports) is to install features

http://drupal.org/project/features

and do a simple feature where you export just a view or a taxonomy set, etc. and use the resulting mini-module as a guide for how you can add this to your own (where I cribbed the above code from)

neilt17’s picture

The key for version in the array returned by YOURMODULE_views_api() should be 'api' not 'version':

/**
 * Implements hook_views_api().
 */
function YOURMODULE_views_api() {
  list($module, $api) = func_get_args();
  if ($module == "views" && $api == "views_default") {
    return array("api" => "3.0");
  }
}

See: Drupal 7 documentation; Drupal 6 documentation.