I am new in Drupal development. There is an TODO item for token.module in the nodereference module. Due to the urgency of using such function, I have implemented such function as follow. Please comment on this. Thanks !

in function _nodereference_potential_references right after the TODO item

      // TODO: Support Tokens using token.module ? ==> only global token is applied
$field['advanced_view_args']=token_replace($field['advanced_view_args'],'global');

in function nodereference_field_settings after the argument field is set. Which is borrowed from automatic node title module.

//add token list for view argument in advance setting
if (module_exists('token')) {
$form['advanced']['token_help'] = array(
'#title' => t('Replacement patterns'),
'#type' => 'fieldset',
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#description' => t('Prefer raw-text replacements for text to avoid problems with HTML entities!'),
);
$form['advanced']['token_help']['help'] = array(
'#value' => theme('token_help', 'node'),
);
}
//

Comments

Version:5.x-1.6-1» 6.x-2.x-dev
Assigned:Unassigned» jpsalter
Status:Active» Needs review
StatusFileSize
new1.84 KB

This patch should do the trick.

Hi,
Does this patch mean that the view arguments like, $args[0] as the first argument behind the base_url with views, will be having token suppurt? what will be the token then?
If so, could you please also make a drupal 5 patch please?

Thanks a lot in advance for considering!
Greetings,
Martijn

This patch enables the passing of token values -> generated from the node your are editing -> to a view -> that returns a list of nodes (filtered by your token value) -> for selection in the nodereference autocomplete.

I hope that makes sense.

Hi,
Thanks for explanation. For me a needed patch! Will there also come a drupal 5 patch please?
Thanks a lot in advance for considering!

greetings,
Martijn

I've just tried to update from cck 6.x.2.0-rc4 to 6.x-2.x-dev patched and I got this error:

PHP Fatal error:  Class 'views_handler_filter_float' not found in mysite/sites/all/modules/cck/includes/content.views.inc on line 187

hope it could be helpful..

That's because cck -dev requires current Views -dev : http://drupal.org/node/95897

sorry, but there is something I can't understand: I created 2 cck nodereference field. The first one takes a list of nodes, and the second one takes [field_first-title] as argument to pass to a view.
When I create a content I choose a node in the first field and I expect something changes in the second field.. but nothing happens.. should I have something else installed to automatically refresh my selections? JQ? Something like Active Select?

The two nodereference fields are not aware of each other and would require custom code to interact.

marked #183997: Make tokens available to nodereference advanced views arguments as duplicate
That post has another patch (for D5), with a slightly different approach (uses a 'general' context instead of a 'node' context)
I'm not extensively familiar with token and I guess i could go either way, so I'll wait on someone to RTBC one or the other approach.
I wonder whether it's an issue that the 'code' context will not be set when creating a new node, though.

StatusFileSize
new2.11 KB

I was redirected here from a similar issue (http://drupal.org/node/183997) for the d5 branch. The patch in #1 didn't apply for me. Updated patch attached rerolled against the current dev branch.

Tested latest patch with latest dev, and appears to work fine. Thanks!

Status:Needs review» Needs work

Hi,

I had just tested this patch and it didn't work for [og-id], [ogname] and [ogname-raw], even if there is an URL argument set (in this case, &gids[]="gid_number"). I believe that it isn't this patch's fault, but that tokens for Organic Groups may not previewing be catching info for adding or editing nodes.

subscribing

Vuds (#12):
Are you trying to use [og-id] on a node/add page? That's what I was trying to do before I looked at the og token code. It only works for the node context, which we don't have when adding a new node (despite the gids[] variable in the URL).

This patch also only fires the token replacement when you're editing a node (it parses urls like node/%/edit to get the node id). It's easy to expand to the global tokens, but you still don't get [og-id].

I'm not sure how to get the [og-id] token to work on a node/add form. If PHP could be used for the nodereference view argument...that would work.

"If PHP could be used for the nodereference view argument...that would work."
there is another patch for that here http://drupal.org/node/334121
but it's drupal 5. Let's see..

just updated the patch to 6.dev, take a look!

subscribe... definitely needs an update since nodereference.module is now node_reference.module.

Status:Needs work» Needs review
StatusFileSize
new2.24 KB

my bad, i'd grabbed views HEAD rather than DRUPAL-6--2. here's an untested re-roll that applies cleanly.

Does not work on d6.8 with clean url and

$matches = array();
           preg_match('`node/(.*)/edit`', $_SERVER['HTTP_REFERER'], $matches);
           $nid = $matches[1];

but it work fine with simply $nid = arg(1) ;

Instead of just token support, maybe it should support the views "argument default" and "argument validator" plugins.

good idea, anyone up to the task?

On the other hand, that is already possible; just use a field specific view and set "argument default" handlers for it.

subscribe

subscribe

subscribe

subscribe

subscribing

Subscribing - this should be committed asap.

NikLP, you should know better than to toss off a "this should be committed asap" without at least reviewing the patch.

@drewish : this looks fine, could you feedback on #19 ?
+ would be good to mirror this code in userreference (noderef and userref are almost exact duplicates)
(+ code style : if(...) { )

We'll be rolling a 2.3 release in the very next days, I'd be happy to include this if the remarks above are addressed.

Also : is it safe to do "replace tokens on the whole comma separated string, then explode into arguments" ?
What if a token replacement introduces a comma ? Should we explode first and token-replace on each argument ?

StatusFileSize
new2.05 KB

What about this, slightly, different approach?

StatusFileSize
new2.22 KB

oh, i see what you're saying in #31. in that case i think something like this might be a bit better.

re #33 : hmm, in this case $view_args wouldn't be an array anymore, right ? which I think Views won't accept ?
+ I think we still want to be able to pass an array of arguments. Comma separated args might be tedious with tokenized strings, a textarea with newline-separated strings would be more appropriate, but in this case we need an update function to update existing noderef fields :-(

[edit : oops, scratch that, token_replace() works with an array of strings, my bad]

Support for this would be great, coupled with that for the other issue for php in that field as well. The issue is here: http://drupal.org/node/334121

I know that's off topic, but it had gotten a little buried and is reasonably closely related, so I thought I'd just pop in a reminder here :)

StatusFileSize
new2.19 KB

There was an offset when I tried the patch from #33 as well as a couple of small syntax errors on line #43. Fixed and rerolled against the current dev. Seems to be working so far, but haven't a chance to test many of the tokens.

yched in #30, i looked at adding tokens to userreference but it's not obvious to me what we should use as the source of the tokens. the node? the current user? the node's author?

I'd say the node as well. Pattern is the same : you want to refine your list of 'referenceable items' based on the referencing object properties.
D7 will be fun, with fields on non-nodes ;-), but at least here we can be sure that the referencing object is a node.

StatusFileSize
new4.06 KB

cool, here's WorldFallz's fixes applied to userreference as well.

Status:Needs review» Needs work

One problem I've got with the patch in it's current form is that you can no longer call return drupal_get_form('foo_node_form', $node); from you're own menu handler. the auto-complete won't work with arg() or menu_get_object(). i think we'd need to pass the nid to the autocomplete menu handler though it's not clear to me what the best way to do that would be.

yched had another good point on IRC:

yched: Also, the problem is that any solution will rely on $node = node_load($nid) at some point. Meaning, token replacement (and thus autocomplete suggestions or input validation) will happen based on the node values in the db, not the node values being edited.

Assigned:jpsalter» Unassigned

I have not been following this thread closely so I'm not sure if this is the same problem.

But, if you're looking for the nid of an edited node calling the autocomplete: http://drupal.org/node/196518#comment-875126 (attached patch in comment #1)

<?php
preg_match
('`node/(.*)/edit`', $_SERVER['HTTP_REFERER'], $matches);
$nid = $matches[1];
?>

jpsalter, that totally fails in the circumstances outlined in #40.

update: also see #19 for more problems.

@drewish #40: This is quite hard to do, I think.

_nodereference_potential_references() is invoked in several places. Some are easy to get the current node state, but some are not.

- From hook_field('validate') is easy to pass $node to _nodereference_potential_references().

- From nodereference_autocomplete_validate(): Here it is quite difficult as we only have $form_state['values'], which might still need processing by other FAPI validate handlers to be able to extract a valid $node object.

- nodereference_allowed_values() is also hard because this hook does not get a $node object.

- nodereference_autocomplete() - this is the menu callback for the autocomplete request. Even if we know the nid, we cannot easily extrapolate the current state of the node being edited, which is in the form. Also, the nid wouldn't be available when creating a node, until the form is submitted. The AHAH requested attached to the autocomplete widget would have to be extended to process the node edit form (like the add more values ahah), and then extract a valid $node object that can be passed to _nodereference_potential_references().

We call _nodereference_potential_references() (through nodereference_allowed_values()) to determine the values to list in Views filters for noderef fields.
In this context, we have no node either.

About autocomplete / AHAH : markus proposal stands, but is quite some work.
OTOH, a select widget wouldn't get updated along with node values being edited either, so why should the autocomplete widget behave differently...

Building the series of API functions that allows the feature by passing along a $node but still behave OK when there is none is not an easy task. The past has shown that this area is a little touchy : many consumers and several providers for 'allowed values', all with their slightly different needs...

Looks like this is a little too far off for a 2.3 inclusion :-(

subscribing

A similar discussion is underway in the Hierarchical Select issue queue: #257922: Hierarchical Select for Node Reference fields.

Could the AHAH Helper module help with the live form alterations?

I've found bit of a hack where I just implement hook_views_pre_build() and check the $view->name and that $view->current_display == 'content_references_1' then just manually set the $args array. The downside of doing it at that point is I don't have the full form but the arguments I needed are in the URL. For the autocomplete I'm going to do some form_altering and stick an #after_build in to alter the callback path.

Subscribing...

Is there any reason, why you are not calling token_replace for the default global type?

subscribe

subscribing

subscribing too

I've been following this thread and several like it trying to come up with a solution to my node reference issue. I desperately need a way of referencing nodes that are filtered by user id. I was excited to see the advanced views option, but frustrated when I realized that arguments have to be hard coded. I've spent the last two days applying patches, trying different modules, even trying rules to pass token values into the views. No luck. I'm looking for any suggestions that you all may have. Be it hacks, patches, modules, rules.

You'll find my use case and code base described below. I'll also go into a few of the things that I've tried so far. Thanks.

USE CASE

I'm trying to create a simple photo and image gallery system using CCK and Views. I want users to be able to create Albums, and Photos independently. And so I've setup two content types within CCK (Photos, Albums). When a user creates a photo I'd like for them to be able to specify an Album via node reference. BUT I don't want them referencing the photo to all the Albums on the site. I only want them to see a list of Albums in which they've created.

CCK Content Types:

1. Photos: Has a node reference field called Albums, points to an "albums view" that I created (The view accepts an argument for the user id).

2. Album

FAILED ATTEMPTS

1. Applying the patch shown here.

I'm using the latest version of Acquia. It includes this version of the nodereference module (nodereference.info,v 1.8 2008/04/23 18:02:07, or 6.x-2.5). Using my Mac's terminal I successfully applied the latest patch provided here. The patch updated my nodereference module so that my "Album" field now shows a list of token options. I tried entering several different token values that were suppose to turn into the user id. However they were never updated and from what I can tell using the Devel module the tokens remain unfiltered.

Q: Is this an issue with the version of the module that I'm using? Did this patch work for anyone else?

2. Using an alternative to the node reference module

Honestly, I've lost track of all the modules that I attempted to use. Some of them included:

- View Reference
- View Attach
- Node Relativity

None of them really fit the bill.

Q: Are any of you aware of how to leverage one of these modules to accomplish node reference with Tokens, or at a minimum by user id?

3. Using a token filter

I installed the Token filter module, which allows users to put token values (e.g [token global site-name]) into text fields. The views arguments field is a plain textfield so I attempted to hack it a bit to make it a text area, I also tried to add a filter option within the form to allow for non-plain text editing. No dice.

Q: Had I been successful in hacking the views argument field into a field capable of using filters would this approach have worked? What would I need to change to make this happen?

4. Using the rules module

I came across another thread where a user said they were able to use rules (as in the rules module) to manipulate the node reference field. I installed this module and I thought that I had a successful set of rules but it didn't pan out.

Q: Would something like this have worked? The whole rules module kind of makes my head spin and I'm not too sure if I implemented it correctly.

I apologize for the lengthy post. Thank you.

@strayhand just add the filter for "User: Current".

@strayhand: If you need to add more stuff... try using hook_views_pre_view(). You can dynamically alter the view, and for example you could add filters based on something that you can guess from this context.

@WorldFallz - Wow, how did I miss that? Thanks.

@markus_petrux - How would I use hook_views_pre_view() in this situation? Because it's a hook i'd have to write my own module or something to actually make use of it correct? I looked it up at api.drupal.org and didn't find a reference. I'll poke around some more and see what I can find.

Thanks guys.

hook_views_pre_view() is exposed by Views module.

http://views.doc.logrus.com/

@markus_petrux - Great it looks like the views module has it's documentation inside the advanced help module also. Thanks again.

For future reference also check out the nodereference_url module which totally rocks.

So... just wondering what the status is.. Would love token availablity

subscribing!

Title:Token support for advanced view argument Token support for advanced view argument

(fixing white space)

In regards to #60, using nodereference_url solves part of the problem, because the module can pre-populate its CCK fields during the content creation process.

Scenario: A dynamic bus schedule

The idea is to have a collection of departure times that can be displayed as tabular data (columns and rows) with the columns being bus stops, and the rows being single iterations or "scheduled runs" of buses along this route. There can be multiple runs of this route every day, thus multiple rows. We'll use Views for outputting this display, but for the purposes of this discussion, I'll only cover the CCK setup and data-entry process.

Content Types

Bus Route - A generic container content type for Bus Stops and Scheduled Runs.

Bus Stop - Defines a physical location along a given route. Has the following node reference:

Scheduled Run - Defines a single pass of a bus down a route. This is yet another container content type for Departure Times. Has the following node reference:

Departure Time - Defines a specific time that a bus departs from a Bus Stop on a given Scheduled Run. Has the following node references:

  • Scheduled Run (using nodereference_url)
  • Bus Stop (a regular Node Reference that uses a select list widget)

Content Creation

  1. I create a new Bus Route node by filling out the form, giving it a name. There are no other fields. I save the form to view my new Bus Route node. (Later, this is where the tabular View results will display, showing all Departure Times organized by Bus Stop and Scheduled Run.)
  2. Thanks to my nodereference_url setup, my Bus Route node has two links at the bottom which read "Add a Bus Stop" and "Add a Scheduled Run", respectively. I click the link to "Add a Bus Stop". I am taken to the Bus Stop form, where I give it a title and so on. The noderef field for "Bus Route" is already pre-populated with the name of my Bus Route node. This is a single value that cannot be changed. I save the form and I'm returned to my original Bus Route node with the two links to "Add a Bus Stop" and "Add a Scheduled Run". I repeat this step several times to add multiple Bus Stops which point to my Bus Route.
  3. When I have entered all of the stops along that Bus Route, I click the link to "Add a Scheduled Run". This takes me to the Scheduled Run creation form. I give it a name. It has no other editable fields. The node reference to "Bus Route" is already pre-populated with the name of my Bus Route node. Again, this is a single value that cannot be changed. I save the form to view my new Scheduled Run node.
  4. Thanks to my nodereference_url setup, my Scheduled Run node has a link to "Add a Departure Time". Clicking it takes me to the Departure Time form. I give it a title, etc. The node reference to "Scheduled Run" is already pre-populated with the name of my Scheduled Run node, which is a single value that cannot be changed. The other node reference is a select list of all the "Bus Stop" nodes.

The trouble comes when we create more Bus Routes with more Bus Stops. In Step 4 above, the "Bus Stop" select list will show all of the nodes which match the content type "Bus Stop", but we only want to see the Bus Stops which are associated with the given Route. Therefore, we create a View called "bus_stops" which takes the node reference to "Bus Route" as an argument, and returns a list of the appropriate Bus Stops. While editing our Departure Time content type, the node reference field to "Bus Stop" has an "Advanced - Nodes that can be referenced (View)" option which allows us to populate the select list with the results from our "bus_stop" View.

The question is, how do we pass the value of the "Bus Route" node reference as an argument? Since that value was pre-populated in the content creation process, it seems like it would be possible to tokenize that value and pass it as an argument. This would save us the hassle of autocomplete suggestions or input validation mentioned in #41.

Subscribing.

@Fr0st,
you described it perfectly, I have exactly the same problem!

Have you solved this issue somehow?

subscribing too

To #64 - I used the patch http://drupal.org/node/334121 - to add a Add PHP code textarea for views argument. So you can programatically set the other NR as an argument.

@2400media2:#67

Did you get this to work? I'm trying it, but I cannot get it to return anything.

Can you give some example code?

@ifoundthetao:#67

I got it to work. It actually turns out that the patch wasn't applied properly when I was using it against the 2.6, but it worked when I used it against the 2.dev. Which I should have been using. ID-10-T error.

subscribe

Concerning the patch code.

Even though $node->nid might be empty, we might still wish to have global tokens working.

For instance, I do so when creating a new node (and so have no saved node yet), so I pass a necessary parameter in URL. I also implement hook__token_values in my module, so I can have the view argument I need.
(Well, I know I could do the same with PHP hook patch)

@Fr0st in #64. Any luck getting this to work?

subscribe

subscribe

Does anybody have an idea how this would get handled in D7 fields in core?
That is, token support for advanced view argument so that the node reference select list knows about fields entered earlier in the add or edit form.
http://drupal.org/project/hs_nodereference looks promising, but intimidating as a D6 solution, not sure about D7.
Just trying to future proof.

The #36 patch works well, it's simple but very effective, please consider a commit!

Ditto -- #36 patch works perfectly and I'd suggest committing it.

#36 works like a charm! Please, commit it officially...

Please commit this patch for it works very well. "http://drupal.org/files/issues/nodereference_196518.patch"

Status:Needs work» Reviewed & tested by the community

Changed status for commit.
greetings, Martijn

@#79

No, this does not work in all cases...

$_SERVER['HTTP_REFERER'] returns "http://www.example.com/admin/content/node/overview" if my URL is "http://www.example.com/node/31/edit?destination=admin%2Fcontent%2Fnode%2..." so the following line will fail...

preg_match('`node/(.*)/edit`', $_SERVER['HTTP_REFERER'], $matches);

#36 does work in this case...

+++ modules/nodereference/nodereference.module 2 Jun 2009 21:38:18 -0000
@@ -819,8 +832,16 @@ function _nodereference_potential_refere
+      // Support for Tokens using token.module.
+      if (module_exists('token')) {
+        // Load the node from the menu system.
+        $node = menu_get_object('node', 1);

The parameters for menu_get_object are redundant. This could probably be simplified in both hunks using if (module_exists('token') && $node = menu_get_object()) { ...

Powered by Dreditor.

#39 is just what I needed. If I set the filter on the view to current user, that makes it so I can't edit someone else's node without clearing out the nodereference field. This patch lets me pass in the UID of the author of the node. Perfect!

I know all eyes are on Drupal 7 but there's still lots of us on Drupal 6. Several people have said this works for them. Any chance of a commit? :)

Thanks,

Michelle

I'm afraid I'm going to have to take back my comment. While working on something else, I noticed I was getting intermittent 500 errors when editing posts. The error log says PHP is crashing on line 214 of token, which is this:

return str_replace($tokens, $full->values, $text);

I did some dsming and it looks like it's crashing because of this patch. I don't know enough about it to know how to fix it, unfortunately. :(

Michelle

@Michelle, DaveReid, Ozmodiar

Would this mean that the status should be put at "Needs Work" or it should stay "Reviewed & Tested by the community" as marked by Summit in #80 ?

Status:Reviewed & tested by the community» Needs review
StatusFileSize
new7.18 KB

I'm attaching an updated version of WorldFallz's patch from #36 (only for node reference fields). My changes fix support for the autocomplete widget when using node-specific tokens in the arguments for Views, and also address some of the issues raised by markus_petrux in #44.

There are still some bigger issues with this approach. The "allowed values" for CCK fields is really meant to be specific to the field and not to a particular instance of the field (on a specific node). So for example, third-party modules can't look up the allowed values for a field if you use tokens that are specific to a node.

i doubt very much this will getting added at this point-- we should probably direct our efforts to the d7 references project which is still short of d6 cck node- and user- reference functionality.

I have applied your patch and it works great. But can someone tell me why that if the argument is not present, the "Provide default argument" values, within the view, are not used. Say the token is null.

To explain, I have a Node Reference field where I would like to use a token to pass a uid value into the view. If I set the Arguments in the node reference field using this patch and a token of another fields uid, After the node is saved, the view brings up the correct nodes to be referenced. This would be the expected result. But the problem is when the node is being created, I would like to use the "Provide default argument" within the view to then bring up the current users nodes. Which it does, if I do not enter a token in the View arguments: to be sent to the view.

So, if anyone can help, I would greatly appreciate it.

I think i may have figured this out or More like got lucky and pasted code in the correct place. But the following corrected the Node Reference field when the token is null or not available.

I pasted the else statement in twice on lines 899 and 903 and it works.

<?php
// Get arguments for the view.
   
if (!empty($field['advanced_view_args'])) {
     
$view_args = array_map('trim', explode(',', $field['advanced_view_args']));
     
// Support for Tokens using token.module.
     
if (module_exists('token')) {
       
// Load the node from a stored form value or the current menu item
       
$node = !empty($source_nid) ? node_load($source_nid) : menu_get_object('node', 1);
        if (!empty(
$node->nid)) {
         
// Replace tokens using node information.
         
$view_args = token_replace($view_args, 'node', $node);
        }
        else {
         
$view_args = array();
        }
      }
    else {
     
$view_args = array();
    }
    }
?>

Really wish this could get committed to the d6 version, there are still plenty of us using it.

Many thanks to all those that have contributed to this thread!!!

subscribing

subscribing

subscribing

#36 works for me. Thanks so much.

A partial solution (if we need the nid as the argument)
Since whe are in the edit page whe can take the node id directly from url:
http://drupal.org/node/833296#comment-3114718

Thank's for all your work!

Could the maintainer please comment as to whether there's any chance of this being pushed to the D6 version? A handy feature, and D6 is still a supported Drupal version, is it not?

and D6 is still a supported Drupal version, is it not?

Drupal 6 core is supported, yes. Contributed module maintainers are free to drop support for previous versions whenever they want.

Michelle

I am looking for something similar for a userreference field (select list widget). I need to have the advanced_views_arg change based on a value that changes. Has anyone applied a similar patch for D6 to the userreference module?

Alternatively, if I can add some code somewhere that changes the argument when a view page is called, that could work too. It's not a form so I can't use hook_form_alter but there must be another type of hook I can put somewhere - maybe template.php?

I've tried every which way to change it in the view but it doesn't work right - it will only work if the argument comes from the field.