1

Im trying to set up a Contextual filter in drupal views based on the URL.

The contextual filter is operating with a text field that sets the node alias.

I have it working with "RAW value from URL" based on the position (parentpage/childpage/grandchild-page), but the position could change (only parents and child for example), so do i need to use the "PHP code", or is there a better way?

What i want to happen:

"If last section of page url, (grandchild-page), matches field set in contextual filter, then true (show fields).

2
1

Though the solution you have implemented worked but my suggestion is to use the request_uri() instead of the $_SERVER['REQUEST_URI'] because of the following reasons:

  • $_SERVER['REQUEST_URI'] is only available on Apache, whereas request_uri() generate an equivalent using other environment variables.
  • Apache does nothing by default to sanitize the $_SERVER variables so directly using it without passing through the check_plain should be considered unsafe.

So its better to get the URL like this:

$current_url = check_plain(request_uri());

Example: if the url is http://www.example.com/param1/param2/param3 than the $current_url will contain /param1/param2/param3.

Rest you can build the logic to get the last params, there are numerous ways of doing that.

2
  • Thank you! I thought there might be a better drupal way of getting the url. – petergus Aug 29 '14 at 7:27
  • @petergus Always welcome. If it worked for you than pls. accept the answer so that it may others looking for the same. – Ankit Agrawal Aug 29 '14 at 7:57
1

You do not have to use PHP code - there is a module for that: https://www.drupal.org/project/views_contextual_filter_query

OR you could use Context: https://www.drupal.org/project/context_query_param

0

Thank you J. Reynolds for pointing me in the right direction!

I have used the following in "When the filter value is NOT available > provide a default argument > PHP Code"

$url = $_SERVER["REQUEST_URI"];
$url_path = parse_url($url, PHP_URL_PATH);
$basename = pathinfo($url_path, PATHINFO_BASENAME);
return $basename;

($basename is matching the last segment of the URL which is set via pathauto from a custom pseudo title field on my content type, and this field is also used the operational contextual filter in Views.)

enter image description here

EDIT: I also have a Relationship "Content referencing Content from field_related_products" that is selected in the contextual filter.

Please refer to the answer from Ankit Agrawal for a better way to retrieve the URL

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.