2

I am fetching data from two table to my view using View API. How can I add where clause to my view?

My actual SQL query is like:

select field1,field2,field3,t2field4 from table1,table2 where t2field=field1

I come across hook_view_alter() but I dont know how to implement that. Can I use any filter handler in my views.inc file?

1

You can implement hook_view_query_alter() to add where condition.

function MODULE_NAME_views_query_alter(&$view, &$query) {
  if ($view->name == 'view_name') {
    $query->add_where(1,'node.nid',$value,'=');  
  }
}
4
  • can u elaborate parameter you are passing in add_where function...can i add table_name.field_name in place of $value variable..i am implementing this hook_view_query_alter in "views.inc" file – Mukesh Gami Feb 18 '16 at 12:37
  • Yes, you can add it, provided the table_name is already available in the query. Or else you need to add the table to the query. For more info, refer this question stackoverflow.com/questions/16959241/… – Suresh R Feb 18 '16 at 12:44
  • function kfd_views_query_alter(&$view, &$query) { if ($view->name == 'report1') { $query->add_where(1,'kfd_survey_master_survey_id','kfd_other_works_form_id','='); } } i am adding this code right after defining hook_view_data..but its showing whole table...where contition does not showing any effect. – Mukesh Gami Feb 19 '16 at 12:32
  • Try to put dpm($query) after $query->add_where(1,'kfd_survey_master_survey_id','kfd_other_works_form_id','=')‌​;, And check if your table is present in table_queue[] and if your where condition is present in where[]. You will get better idea. FYI, it doesn't matter if it is after hook_view_data or not. – Suresh R Feb 19 '16 at 12:42

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.