Drupal 7 Views – Manipulating Args with php

I wanted to pass a string to a view that only accepts an entity id as an argument.
I the past I’d been able to use a string based argument after adding relationships but that wasn’t possible in this case.

So I decided to override the incoming argument during validation and replacing the string with the relevant entity id.

The use case:

I mentioned that the view only takes a entity id (nid) as an argument. That nid isn’t available to me when I call the view, but I do know a ‘location’ that I can associate with entities.
Ideally the town name “Eugene” is passed to the view but the entity id (237) is what’s used in the view.

The key was to call another view from within my contextual filter argument validation field.
There I pass the ‘location’ name argument to another view (nid_from_townname) using php and the views_get_view() function.
That view returns the nid for the entity in question. So then I override the original view’s argument with the nid and we’re in business.

Here’s a screenshot of the (view display’s contextual filter argument) validation field:
view of the contextual filter edit overlay


Call a view from within a contextual filter argument validation field and replace the incoming arg with the result of the view

Here’s the essential code with comments:

<?php # Don't include this tag
//set the other view's name
$otherView = views_get_view('nid_from_townname');
//prepare the current views display's argument for use in the other view
//execute the other view
//Leverage the other view's result to create a new argument for this view display, i.e. result[0]->nid
$handler->argument = $otherView->result[0]->nid;
//override the argument
return $handler->argument;
# Don't include this tag ?>

I leveraged the var_dump function during testing to sift through the result in order to find craft the result address: $otherView->result[0]->nid;

drupal_set_message('Result: <pre>'.var_dump($otherView->result).'</pre>');

So that’s that.
Now I can display content associated to a location name without knowing the relevant entity id.

  • ibrahim says:

    hi. thanks for article. i want to ask about passing parameter between two display (block to page for contextual filter). i have a display block “author’ other article” which show 10 article. i want add a link “show all article” and to show outhor’ all articles in a page. so i create a block and a page. i can use author’ name in block with contextual filter but how can use the same name in page. i think i should pass block contextual filter parameter (author name) to page’s contextual filter. but i don’t know how to. thank for any help from now.

Leave a Comment