Drupal Questions & Answers

Ask and answer Drupal related questions! No question too simple or complex!
rouderj's picture
Asked by on Mon 1st Dec 2008
How to pass arguments to a block view in Drupal 6, Views 2? The help on the web that I have found seems to assume Views 1.

Hi all,
I am a newbie. I can look up PHP commands but I dont really know PHP. I am setting up a web site for my department (Psychological Sciences, Univ. of Missouri). I am a faculty member so I am doing this on the side for “fun.” One of the things we would like is to list publications and I have built a “publications” content type. Each faculty member has a page (node) and I would like to add a block at the bottom that lists publications for that faculty member. I choose user name as the argument but cant seem to pass the user name from the page (node) to the block. I can get it to work in the views preview if I type in the user name myself.

Thanks in advance,
jeff

Commenting on this Drupal Question is closed.

Answers (65)

DrupalSN's picture

Hi Jeff,

First up, welcome to DrupalSN, hope you enjoy the site!

Here’s how i’d do it:
1) In the view admin page under arguments click on the User:name argument and scroll down the page where you’ll see some options for that argument under “Block: Configure Argument User: Name”.

2) Under “Action to take if argument is not present” select “Provide default argument” then under “Default argument type” select “PHP code” now we can enter some custom PHP code to get the username from the page URL assuming your username is the second argument in the URL
ie. publications/USERNAME

3) Now in the “PHP argument code” box enter the following PHP:

<?php
if (arg(0) == 'publications' && arg(1) != '') {
  return
arg(1);
}
?>

Again I’m assuming the URL is publications/USERNAME and what we are saying here is if the first URL argument is “publications” and the second URL argument is not blank then use the second argument as the views username argument.

4) You should select “hide view / page not found” in the “Action to take if argument does not validate” under “Validator options” that way views will check the user exists and find the view/block is they don’t have any content.

5) Lastly save the view and assign your block to the publications/USERNAME page.

That should do it, let me know if it works, i loaded up views and tested it so should be fine.

Thanks
Tom

rouderj's picture

Tom,
Thank you for your prompt answer. I have to redesign the site a bit, but I will let you know how it worked.
Best, Jeff

wandybrad's picture

customized paper
I agree, this post is a great post. I like to use Facebook, so I like the Module Integration. Facebook-style Statuses integrates with a large number of modules.

faunt's picture

This is a nice walk-through, but I’m having difficulty implementing. The arg(n)‘s seem only to reference arguments in true url’s (as per discussion here), but as I’ve relied on Pathauto’s url aliasing to mimic site hierarchy, I wonder whether my trouble is that the arg(0) and arg(1) I’m calling aren’t what they appear to be in my address bar?

Any ideas for a similar scenario where “publications” and “USERNAME” were aliased, based on CCK fields? Or maybe I’m missing something else altogether?

Any and all help’s appreciated.
Thanks,
David.

DrupalSN's picture

Hi,
First up welcome to DrupalSN!
If you want to use aliases instead of true urls you need to use the drupal_get_path_alias() function (http://api.drupal.org/api/function/drupal_get_path_alias/5).

Here’s an example of how to use it in the views argumemts:

<?php
$path
= drupal_get_path_alias($_GET['q']); //get alias of URL
$path = explode('/', $path); //break path into an array
//user print_r($path); to see what the $path array looks like
if ($path<a href="#fn41007476353f4fec46514e">0</a> == 'publications' && $path<a href="#fn190484410653f4fec46520a">1</a> != '') {
  return
$path<a href="#fn190484410653f4fec46520a">1</a>;
}
?>

So $path is broken down into an array so we can use the array chunks much the same as we do with arg().
Here’s an example path to help you:
path alias = publications/username
$path0 = publications
$path1 = username

Hopefully this will get you going!
Thanks
Tom

faunt's picture

Really awesome feedback. I’m happily amending my Views across the board to include arguments of this form. Thanks Tom.

jkler's picture

rilliant stuff, man! What you have to say is really important and Im glad you took the time to share it. What you said really spoke to me and I hope that I can learn more about this. Thanks for sharing your opinion. I am yet to find anything as enlightening as this on the web.Thank you for share!
Juicy Couture Outlet

faunt's picture

Followup question re: negation.

I promise not to exploit your support by posing every challenge I encounter from here-on-in, but wonder if I can ask one followup question that I think will resolve all my latent confusion with arguments in Views:

I’m hoping to apply a version of this PHP handler that returns all nodes not equal to a particular argument in the aliased domain. In the example used in this discussion thread, the argument returns all nodes matching the current url’s first argument, $path0 = 'publications', but I want the argument to query the present url’s $path0 and return all nodes of a different value.

i.e. ‘publications’ might be a taxonomy term, aliased on all nodes using Pathauto, but I want my view to return all nodes with different terms in the $path0 argument of the url, excluding the current value (‘publications’).

To be clear, I’d be issuing this in conjunction with other arguments that exclude nodes based on contents of $path1 and $path2, so I could still filter by USERNAME, or other arguments in the aliased url.

Is this in fact a job for arguments? Or should I be using filters? Any insight?

I should specify that I can see how the following would work if I merely wanted to exclude ‘publications’:

<?php
$path
= drupal_get_path_alias($_GET['q']); //get alias of URL
   
$path = explode('/', $path); //break path into an array
    //user print_r($path); to see what the $path array looks like
   
if ($path<a href="#fn41007476353f4fec46514e">0</a> != 'publications' && $path<a href="#fn190484410653f4fec46520a">1</a> != '') {
      return
$path<a href="#fn190484410653f4fec46520a">1</a>;
    }
?>

I’m looking for a way to do this dynamically though (as I have a lot of taxonomy terms, and don’t want to make a unique view for each if I don’t have to). I tried the following without success:

<?php
$path
= drupal_get_path_alias($_GET['q']); //get alias of URL
   
$path = explode('/', $path); //break path into an array
    //user print_r($path); to see what the $path array looks like
   
if ($path<a href="#fn41007476353f4fec46514e">0</a> != $path<a href="#fn41007476353f4fec46514e">0</a> && $path<a href="#fn190484410653f4fec46520a">1</a> != '') {
      return
$path<a href="#fn190484410653f4fec46520a">1</a>;
    }
?>

DrupalSN's picture

Hi,
No problem with the questions, feel free to ask as many questions as you like and we’ll try to answer!

I’m not sure i understand you fully.
Is this for a node view page, do you want to get the taxonomy term from the node being view or is the taxonomy term in the URL?

Thanks
Tom

faunt's picture

The taxonomy term is the first arg in the aliased url being viewed, i.e. example.com/term1/.

I actually figured out a workaround for the interim, though, which helps with a theming issue I would have encountered. Quickly, I decided to clone my view for each taxonomy term (only 4, so possible), using filters and block configurations to customize when these appear on different node pages. I’ll try to clarify down the road with a new post when I have a bit of time.

Thanks for your attention on this,
David

jkler's picture

Your blog article is very interesting and fantastic, at the same time the blog theme is unique and perfect, great job. To your success. One of the more impressive blogs I’ve seen. Thanks so much for keeping the internet classy for a change.
Juicy Couture Outlet

Blueieee's picture

Hi Tom,

I’ve just moved from Views 1 to Views 2 and I’m still struggling with the changes. So it would be great if you could help on this.

My pages on Drupal are aliased using pathauto, but I’m trying to retrieve my node id and pass it in as an argument. The methods you described above would help me to retrieve the alias of the page, but that isn’t sufficient to pass to views to process and retrieve the related information for me.

So my question is how do you retrieve the node id from the alias of the page?

regards,
Jamie

DrupalSN's picture

Hi,

Even if you’re using pathauto the nid is still in the url in the arg() function.

So your url might be “news/jan/drupal-is-eight” but the “true” url is still node/NID.
To get the nid you can use the arg function like so:

<?php
//check we are on a node page first
if (arg(0) && is_numeric(arg(1))) {
 
$nid = arg(1);
}
?>

Hope that helps
Tom

Blueieee's picture

Hi,

Thanks for the reply. Let me illustrate my problem a bit further.

I’ve got 2 content types, shop and product, and product has a node reference field to shop.

I’m trying to create a view to show all the products listed by a shop (the url assigned to the view is shop/%/products, and the argument added is the node reference field).

The view has no problem displaying if the argument is a node id (eg. shop/1/products). But I want to use the url alias of my shop instead of the node id. Thats where I have a problem since I’m not sure how am I supposed to craft the argument handling code.

I know how to do this in Views 1, but I’m quite lost in Views 2. Hope you can help guide me a bit on this.

Thanks.

Jamie

Prodigy's picture

The URL should probably be $arg rather than %.

Are you using PathAuto?

arilikeairy's picture

How do PathAuto and Views work together? If I want to grab an argument (i.e. arg(1)), does the result come from the system URL or the pathauto URL? If the former, how do I use information in the pathauto URL? Thanks!

Ellaly's picture

That’s looking neat.. nice set of code to make drupal more user friendly as well as attention capturing!juicy couture tracksuits

foreman's picture

I have to say that I also found the information here quite useful and I’m also trying to learn PHP. Hopefully, I’ll manage to cook a fast burger on the best grill pan in my opinion that is made of cast iron, and I also think that it’s better than the foreman grill grp99 that I had in the past and was fine as a bbq but not that good. Anyway, I hope to read more informative stuff on this site.

ridder64h's picture

I’m hoping to apply a version of this PHP handler that returns all nodes not equal to a particular argument in the aliased domain. In the example used in this discussion thread, the argument returns all nodes matching the current url’s first argument דילים

Progression Holding LTD's picture

I have exactly the problem you describe with Views 1.x. How did you solve it ?

Asghar's picture

Hello to all
I am using Drupal 6 when i add the above code in view argument
title and create a node it work fine but a warning display

“warning: implode() [function.implode]: Invalid arguments passed in C:\wamp\www\listur\sites\all\modules\views\plugins\views_plugin_argument_default_php.inc(48) : eval()‘d code on line 7.”
why this warning is displaying?

tootsietorres's picture

I found this really helpful, but unsuccessful.

I am trying to use the last term in the pathauto supplied URL as the argument. My URL is www.mysite.com/communities/area1. If I just type:

  return 'area1';

it works fine. But I wanted something a little more dynamic, like:
  $path = drupal_get_path_alias($_GET['q']);
  $path = explode('/', $path);
  if ($path0 == 'communities' && $path1 != '') {
    return '$path1';
  }

Any suggestions on what I’m doing wrong?

DrupalSN's picture

Hi,

Don’t think you need the ‘’ round $path1:

<?php
$path
= drupal_get_path_alias($_GET['q']);
$path = explode('/', $path);
if (
$path<a href="#fn41007476353f4fec46514e">0</a> == 'communities' && $path<a href="#fn190484410653f4fec46520a">1</a> != '') {
  return
$path<a href="#fn190484410653f4fec46520a">1</a>;
}
?>

That should work
Tom

tootsietorres's picture

Thanks for replying so fast Tom.

I removed the ‘ ‘ around $path1, but it still didn’t work. I actually didn’t have them there originally, but I tried hard coding return ‘area1’; to see if it worked (which it only did when I removed the if statement did). Does that provide any more clues?

Tootsie

DrupalSN's picture

Hi,

I’d print out the $path array to check it’s producing the results you’d expect:

<?php
print_r
($path);
?>

You may need to move the code to the Views header and select PHP code as I’m pretty sure the argument handling code won’t return the printed variables on screen.

Then check the if statement is returning true by printing some text out within the if statement:

<?php
if ($path<a href="#fn41007476353f4fec46514e">0</a> == 'communities' && !empty($path<a href="#fn190484410653f4fec46520a">1</a>)) {
  print
"if statement true";
}
?>

If no of these resolve the issue i’d open up a new question and i’ll take a closer look.
Tom

letharion's picture

I have the same problems with not getting things to work.
May I have how to
“You may need to move the code to the Views header and select PHP code as I’m pretty sure the argument handling code won’t return the printed variables on screen.”
so I can try debugging with that?

yakker's picture

Just in case it helps – I was having trouble getting it to work too, but it was an error on my part.

Make sure you do not include the <?php and ?> tags in your PHP default argument code. :)

Also, to debug, you can paste the print_r(...) in your page.tpl.php right below or above the $content variable.

Hope this helps (hope it’s correct!)

Chris

pollitt4g's picture

I actually figured out a workaround for the interim, though, which helps with a theming issue I would have encountered. Quickly, I decided to clone my view for each taxonomy term (only 4, so possible), using filters and block configurations to customize when these appear on different node pages. טיסות זולות

superwork's picture

I have found this your post because I have been searching for some information about it almost three hours. You helped me a lot indeed and reading this your article I have found many new and useful information about this subject. Thanks for your insight for the great written piece. I am glad I have taken the time to read this.

casino en ligne

Chuckie's picture

Hi Tom,

everything you have said makes sense, but it this dog just won’t hunt.

I put the php code into the node to make sure it’s grabbing the argument, it is.

So I am referencing %1 in the argument section and just in case that fails, I’m using your php code to grab the URL and process it.

It continues to return no data despite the preview showing the data.

I’m very frustrated, if anyone else had this issue, please let me know.

d_nice's picture

Hi Tom,
Is there a way to make this code work with 2 arguments?

For exmaple, can you have publications/USERNAME/term2 and pass them both into a block display on a view?

thanks!

johnalbert486's picture

This is highly informatics,
crisp and clear. I think that Everything has been described in systematic manner so that assignment help reader could get maximum information and learn many things. This is one of the best blogs I have read.

renuka's picture

Languages Courses in Bristol. Choose from 69 languages courses, languages classes, languages education and training options in Bristol.
Bristol Language Courses

Wavelength Design's picture

Tom’s reply here solved for me an issue I had been grappling with, so thank you Tom very much. However, I think as a result I’ve come up with an even simpler solution that does not require any PHP code, so may be easier for people to implement and remember how to re-use in the future. See the tutorial I’ve posted on the topic. :)

gregocelt's picture

ok, but what if the path and taxonomy are different?
for example i have tax: Robbie Williams
and path www.blablasomething/robie-williams

[basicaly on my album page i’m displaying list of taxonomys like:
-artist
-album title
etc

and i want in the block to display different (more) albums of the same artist
]

i am affraid i will lose my mind over this!! and PHP is not my thing, please help

gregocelt's picture

and in my case the Argument need to be Taxonomy Term and alias is differnet the taxonomy,
example of one of my taxonomy, ‘artist’:
i have Robbie Williams
but in the path is robbie-williams

how can i solve that coz it is obviously did not match! what is taxonomy structure for that?

DrupalSN's picture

Hi,

In the taxonomy argument settings do you have:
Case in path: lower case
Transform spaces to dashes in URL: checked

I’ve heard that you can’t use url arguments with block displays in views 2 but give it a try and see. if not you’ll need to play with the PHP Validate code to set the argument manually, this page may help: http://drupal.org/node/258801#comment-850224

Tom

Real Tidings, LLC's picture

Tom – fantastic responses. I used this code to get the term from the auto-url alias and only display the related values:

$path = drupal_get_path_alias($_GET['q']);
$path = explode('/', $path);
return $path0;

Works like a champ!

timoffei's picture

I get “page not found” error when i implement views 2 blocks with arguments, pathauto turned on. The page node where block is placed shows map, upon clicking on a certain region, flash redirects the page to page-with-map/region. there the page node is not displayed, but views block is displayed under page not found title.
However, when i view the node with raw urls like node/6/region block and page shows up perfectly

Do you have a solution to a problem like this?
Need help :)

timoffei's picture

No answers, though, i solved the problem with querystrings:
ex:

page-with-map?region=value.

and php code
if (isset($_GET['region'])) {
return $_GET['region'];
}

any comments on security issues?

etcetera9's picture

Tom’s answer on his second comment (http://drupalsn.com/learn-drupal/drupal-questions/question-2650#comment-563)
works if you just omit the first and the last lines (php tags) since that php box on the “provide default argument” section clearly states you shouldn’t use them…

johnathan's picture

I can get the block to accept the arguments, but whenever I try to use mysite.com/projects/2009 (where 2009 is the argument), I just get a 404 page.

Hasn’t anybody else hit this problem?

Right now I just have the block display on every page, so even on the 404 page I see that it’s accepting the arguments.

How should I implement this method without getting 404 pages?

eyewear's picture

I like to say that This blog again looking too interesting I got a nice and great read on this blog. this time I want to thank along with my whole team. We also like to thank to blogger for his best thinking.
discount prescription eyeglasses

mugi's picture

hi tom i need ur help
i want to pass the argument(state value) to ‘leader view’.based on that it should display the particular leader details .how to do please help me .sorry for my bad english

ID Sketch's picture

i need help on the same, thanks mugi for raising the same question on my mind.
SEO Company

francis yip's picture

What’s wrong with this PHP ?

I have been banging my head against the wall trying to get this to work. In theory it seems straightforward but not so in practice.

I am using D6 6.17 and latest Views2.

I have created a content node ( pathauto generated url alias is content/feature )which will act as the “container” to display Views Block and what is displayed is dependent on the argument passed to it using the method described in this post.

In views I have the argument setup and tested .. for example I have successful output in Views UI for teh argument “highlights”.

This is exactly what I placed in the PHP argument code field:

$path = drupal_get_path_alias($_GET['q']); //get URL alias
$path = explode('/', $path); //break path into an array
if ($path0 == 'feature'&& $path1 !='') 
   { return $path1;
}

this url will return “page not found”
example.com/content/feature/highlights

and if I change the url alias from “content/feature” to “feature”
teh result is still page not found.

I also have the same negative result even if I changed the php to from $path0 to $path1 and $path1 to $path2 thinking that perhaps it is because the array containing the exploded url alias has 3 components ( of Content / feature / argument and therefore teh PHP code should start reference $path1 for feature and $path2 for the argument) but it still does NOT work

Any help will be greatly appreciated.

thanks alot!

thatguy's picture

Try this:

$path = drupal_get_path_alias($_GET['q']); //get URL alias
$path = explode('/', $path); //break path into an array
if ($path0 == 'feature'&& $path1 !='')
   { return $path1;
}

I don’t really know how you can call out an array without having the brackets [ ] around each variable in the array. Also you may need to change the number in the brackets depending how deep the path is.

If you don’t care about checking the path before you could simplify to this and just change the number in the array to how deep the path is. Voila!

$path = drupal_get_path_alias($_GET['q']); //get URL alias
$path = explode('/', $path); //break path into an array
return $path1;

EDIT: HERE IS THE PROBLEM. This drupal Web site is stripping out the brackets from the array [ ]. So the variables should be $path(1) where the parenthesis are actually brackets [ ].

I see this causing all kinds of havoc throughout this site and should be fixed as when people post code it is inherently broken causing massive headaches. I think it’s turning the items into URLs. AS you can see the 1 and 0s in the $path variable are turned to cyan blue links.

Als's picture

Your “edit” is very important.

I too did not understand the reason for the meaningless links within the code.
The system might be converting numbers within square brackets to HTML anchors.

Site admins fix this, it ruins your nice work!

any's picture

Thank you for the explanation it’s worked on my site!

I would be grateful if you could give a hint on how to use a more complex argument – I wish to display documents by academic year, e.g. in the URL /documents/08-09/. Doing it by calendar year would be simple, I would just return 2009. How can I ask it to return everything between september 08 and august 09?

So far I have

$path = drupal_get_path_alias($_GET[‘q’]);
$path = explode(’/’, $path);
$reqyears = $path(1);
$reqyear = explode(’-’, $reqyears);

Now I have $reqyear(0) as 08 and $reqyear(1) as 09.

Thank you in advance for your help!

any's picture

Is it possible to specify ‘greater than’ in the argument, rather than ‘equal to’? Because that would solve it, but I can’t find a way of doing so.