Outputting a Drupal 7 View programmatically with Contextual Filters (arguments)
Ever need to output a Drupal 7 view in your code? If so the views_embed_view function is an easy way to do this. One thing you may not have known, is that you can also use it to pass values into your views contextual filters (what the Drupal views module used to call "arguments").
Here is a quick example of how to output a view in code using the views_embed_view function:
print views_embed_view('VIEWS_MACHINE_NAME', 'DISPLAY_ID');
You can get the VIEWS_MACHINE_NAME by going to the main views listing and hovering over the Drupal 7 View you are trying to output programmtically. This should give you a tooltip with the Views machine name.
You can get the display_id by editing that view and hovering over the tab that you want to display. In the URL that is generally displayed on the bottom left of most browser you will see something like this:
http://mysite.test.com/admin/structure/views/view/my_test_view/edit/block_2
In this example, the display id is "block_2" and the machine name is "my_test_view".
If you want to send an argument into the views contextual filter, simply add another argument to the views_embed_view function.
$my_arg = 1; print views_embed_view('my_test_view', 'block_2', $my_arg);
Side Note: If you are using a date as a contextual filter (as I was in my case), the format of the date is YYYY-MM-DD. So an example would be:
$my_date = "2012-09-07"; print views_embed_view('my_test_view', 'block_2', $my_date);
What do you think? Let me know in the comments below.



Discussions
That's pretty nifty !D
That's pretty nifty !
D
Awesome
So simple and awesome...
Thanks for sharing this, and presenting it in such a concise way!
Would be good if you included
Would be good if you included an example with Contextual Filters (arguments) as the title suggests, and not just one which can seen the the std drupal doc anyway.
Awesome Could give us an
Awesome
Could give us an example of how to recieve the $args on the other view
Thank u very mush
exposed form values
Thank you for the tip!
BUT:What about the exposed form values? How can I add them to the embedded view?
Post new comment