Drupal Setting Views Filter via Cookie

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:
add-filter-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.

Select php code for default when filter not on url string.

Select php code for default when filter not on url string.

Then we supply a blurb of code to read the Cookie value:
php-value-code

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!

Tags: , , , , , , , | Posted under Drupal | RSS 2.0

Author Spotlight

David Gurba

David Gurba

I am a web programmer currently employed at UCSB. I have been developing web applications professionally for 8+ years now. For the last 5 years I’ve been actively developing websites primarily in PHP using Drupal. I have experience using LAMP and developing data driven websites for clients in aviation, higher education and e-commerce. If you’d like to contact me I can be reached at david.gurba@arvixe.com

Leave a Reply

Your email address will not be published. Required fields are marked *


3 × 7 =

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>