0

I want to embed a view in the tpl.php, so I am using the views_get_view('VIEWNAME') function.Here is what I am doing the tpl.php.

<?php
   $view = views_get_view('MapView');  
   print $view->preview('default');
?>

"MapView" is the view's name, I am not sure the argument in the views_get_view is the machine name or human readable name, in fact in my example is using the human readable name, because I can't find the machine name in the drupal view configuration

anyway, I get a error saying "Fatal error: Call to a member function preview() on a non-object", seems like I didn't fetch the view in the correct ?

any idea ?

  • You need a machine name of a View. It can be found in edit url (/admin/structure/views/view/%machine_name%/edit) or with exporting a View ($view->name will contain a machine_name. – kalabro May 19 '12 at 20:30
  • @kalabro I wonder why you chose to make this a comment instead of an answer. It perfectly answers the question the user824624 asked. – Oswald May 19 '12 at 20:44
3

Even thought the documentation for views_get_view() refers to $name as the name of the view, what the function wants is the machine name of the view.

You should always check the value returned from the function is not NULL, as the function doesn't return any value, if it doesn't find the view with that name.

  ctools_include('export');
  $view = ctools_export_crud_load('views_view', $name);
  if ($view) {
    $view->update();
    return $view->clone_view();
  }

views_embed_view(), for example, uses the following code.

  $view = views_get_view($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return $view->preview($display_id, $args);

You should use similar code, avoiding to call $view->access() if the view should always be visible, independently from the permission the currently logged-in user has. If you need to show the view only when the user has the permission to see it, then you should consider using views_embed_view().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.