I have created a view page and a block. I need to get the query from the view block. The query preview can be seen.

The following code was found to fetch the query from view

function status_update_views_pre_execute(&$view) {
 if ($view->name == 'project_initiative') {
   $query = (string)$view->build_info['query'];
   echo $query;

Where is the result of the query stored? How can I fetch it?


the query is as follows

SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, 'node' AS field_data_body_node_entity_type, 'node' AS field_data_field_project_name_node_entity_type FROM  {node} node LEFT JOIN {field_data_field_project_name} field_data_field_project_name ON node.nid = field_data_field_project_name.entity_id AND (field_data_field_project_name.entity_type = 'node' AND field_data_field_project_name.deleted = '0') WHERE (( (field_data_field_project_name.field_project_name_target_id = '55' ) )AND(( (node.status = '1') AND (node.type IN  ('status_update')) ))) ORDER BY node_created DESC LIMIT 10 OFFSET 0

How can I execute it to get the result in drupal custom module?

  • what exactly do you plan on doing with it? – No Sssweat Jun 5 '18 at 5:43
  • @NoSssweat The query will return a set of nodes from which I want to create a timeline with its date fields. – Rony Samuel Jun 5 '18 at 5:47
  • have you tried $query->execute(); ? It will turn in an endless loop if you execute it in this hook, though. To get the results of the views query you should use views_pre_render hook there it will be executed. – Insasse Jun 5 '18 at 5:51
  • @Insasse I have changed the question. please check. The query should have a result. the result is a set of nodes and where or how can I achieve it? – Rony Samuel Jun 5 '18 at 5:55
  • You can execute this query whereever you want, but maybe you want to check this-> api.drupal.org/api/drupal/includes!database!database.inc/group/… first. Depends on the context you need to execute the query. – Insasse Jun 5 '18 at 5:58

You could get the nids like this:

// load and display view
$view = views_get_view('view_name');
$nids = [];
// get all nids from the result 
foreach ($view->result as $result) {
   $nids[] = $result->nid;
// render view
print $view->render();
| improve this answer | |
  • It didn't work for me. Thank you for your response though! – Rony Samuel Jun 5 '18 at 6:24
  • I am trying to explicitly ran the query and fetch the results(node id ) – Rony Samuel Jun 5 '18 at 6:25
  • @RonySamuel should've worked. Did the view print? if not, then you did not enter the correct value in line 1 or line 2. For line 2 you need to set the correct machine name OR unless.. is your view using contextual filter? I did not set that here. – No Sssweat Jun 5 '18 at 6:38

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.