2

I have a view called all_projects_list. This view fetches Fields (not nodes), and i'd like to get it by code, and iterate on it. I managed to do this by using:

$view = views_get_view_result('all_projects_list', 'default');
foreach($view as $project){
    print_r($project->_field_data['nid']['entity']->field_project_code['und'][0]['value']);
}

Which as you can see is very, very dirty. Is there a Drupal way of doing this ? Thanks in advance.

6

It's not very different from what you do, but here's example code from a project of mine, showing how I usually do it

$view = views_get_view('a_view');
$view->preview('panel_pane_1', array($node->nid));
foreach ($view->result as $tid) {
  print $tid->taxonomy_term_data_taxonomy_term_hierarchy_tid;
}

Based on the function documentation

To be called externally, probably by an AJAX handler of some flavor. Can also be called when views are embedded, as this guarantees normalized output.

I've always assumed that preview() is the proper way to do it, and it has served me well on a number of occasions.

  • Is this really the only way of doing this? This is really not pretty (having to get the view data twice just so you can parse it) – Steven May 31 '12 at 15:17
  • 2
    You're not getting the data twice, you're loading the view, then executing it via preview(). You can also use execute(). What are you trying to achieve by iterating through? Views has a very robust API which you can do just about anything in if you can decipher it. – cam8001 May 31 '12 at 15:54
4

you can do this

$view = views_get_view($view_name);
$view->set_display($display_id);
$view->pre_execute();
$view->execute();
$total = $view->total_rows;

to get the total number. If you want to iterate, maybe

$result = views_get_view_result($view_name, $display_id);
foreach($result as result) {
  // do something.
}

Note: this depends on use pager to display all results, otherwise you will get only limited results.

  • 2
    i facing an issue with views_get_view_result($view_name, $display_id); because it returning entire fields that coming in sql query, even those fields are not mentioned in view display settings. How can I get the exact row of data that we are getting from views template file as $rows variable? – ARUN Mar 15 '14 at 10:43

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.