Recently I responded to a question on how to make a Views Filter respond to a Cookie value. Put another way — if I have a View and I want to save off a filter value; how can I populate the filter criteria without having to submit the $exposed_form first. How can Views remember the value from a returning visitor?
The nice thing about this task is that Views provides a mechanism for you to do this from the Views Administration UI. This is true for essentially Drupal 6/7 and Views 2 or 3 at the time of this writing.
Solution:
The concept is to use a Views Contextual Filter (D7 jargon) or a Views Argument (D6 jargon). The terminology here is slightly different between Views versions — but the UI choices are very similar. The following steps are for a Drupal 7 solution:
For any field you want to pull a value from a Cookie you add an exposed filter, here we add a contextual filter for the field, here a node->title:
Then we configure the filter to pull a value from the URL. If none is provided we define how to find the value via PHP code. This is the secret to pulling the value from a $_COOKIE value.
Then we supply a blurb of code to read the Cookie value:
Now the View works as if the filter was applied magically from nowhere!
You’ll note I didn’t cover how the value was stored in the cookie in the first place!? Cookies, can be stored from many many different places and occasions. The cookie key/value pair need simply be stored for the correct domain and your website will have access to it.
Looking for quality Drupal Web Hosting? Look no further than Arvixe Web Hosting!
Hi David, i have one view where i pass the node id to the contextual filter and i want make this in cookie but i have selected multiple values. When i do this by url i do #+#+#… if do the same by cookie the content that i pass is similar ‘#+#+#…’
I believe the contextual filter, when using multiple values, expects an array of values to be returned. On the URL this looks like ‘#+#+#+#’. You would want to do something i your Contextual Filter PHP Code as:
$filter= isset($_COOKIE(‘nids’) : ”;
return explode(‘+’, $filter);
To return the Node Ids as an array of IDs to be used by Views. You can examine your View normally with an exposed filter and the debug module and simply dpm($view);
You can then do the same dpm($view) once you’ve attempted to add code that reads from the Cookie and assure its being passed to the contextual filter ok. Please let me know if you need more assistance.