4

We can create a view from admin panel. But I want to create a view using php code. Can anyone show me the way?

Muhammad Reda
  • 26,379
  • 14
  • 93
  • 105
Al- Imran Khan
  • 187
  • 1
  • 5
  • 14

1 Answers1

7

There is code floating around that wouldn't work for me. But This one did. Add this php to your .module file. Then create a views folder and then put all your views in there with the extension of .inc. Each view file will simply be <?php followed by the exact export of the view...

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

function MODULENAME_views_default_views() {
  // Check for all view file in views directory
  $files = file_scan_directory(drupal_get_path('module', 'MODULENAME') . '/views', '/.*\.inc$/');

  // Add view to list of views
  foreach ($files as $filepath => $file) {
    require $filepath;
    if (isset($view)) {
      $views[$view->name] = $view;
    }
  }

  // At the end, return array of default views.
  return $views;
}
ja_him
  • 417
  • 1
  • 4
  • 20
Jay Shoemaker
  • 71
  • 1
  • 2