Q: How can I pass an argument to a ‘block view’ in Drupal 6?
A: There is no way to pass an argument to a block view in Drupal 6, but don’t panic as there is a way to achieve the same result through some slight-of-hand.
The use of arguments with Drupal views are vital for getting the most out of the views functionality. How are the arguments normal passed to a view? Well, if a view is configured to produce a page then the arguments are easily passed as part of the requesting URL, while if a view is embedded using code, then the arguments are passed in as part of the call to embed the view. But if a view is configured to produce a block, how do you pass arguments to it? The bad news is you can’t – the good news is that there is a way fake it and achieve the same result.
The trick involves providing a PHP handler within the view which will be called when the view is invoked without an expected argument (this is what happens when the block is displayed!). We just arrange for this handler to retrieve and return the argument’s value and then the view will behave as required – just as if the argument had been passed to it in the first place.
To do this create the block view as normal and configure the required argument(s). For each argument we choose the ‘Provide default argument’ option, and select the ‘PHP code’ sub-option. We then provide some PHP code which will ‘get’ and return the argument’s value, it doesn’t really matter where or how the PHP code gets the argument once it returns the correct value. Have a look at screen shot below:
The example above is a bit simplistic as the PHP code just returns a static value – not very useful at all! A more realistic or useful example (inspired by one of the posts referenced below) would be to return the argument that was passed to the page that contains and displays the block. Consider the mythical paths:
Here things are set-up so that ‘web-design’ and ‘illustration’ are arguments to the ‘projects’ page, they result in only the projects of that type being displayed. Assuming we are using the pathauto module for nice clean URLs (as we almost always are!) then the following PHP code when provided as the default argument handler will get the URL, parse it and return the argument part to the view.
$path = drupal_get_path_alias($_GET["q"]); //get URL alias
$path = explode("/", $path); //break path into an array
if ($path == "projects" && $path != "")
So there is is, it’s definitely not the easiest method in the world but at least it does provide a mechanism of getting those arguments to the view…