Updated: Comment #10

Problem/Motivation

Entity Reference allows using a View of a specific display type to set the available options. It's also possible to set arguments (contextual filters) on that view from the ER field config screen.

The problem is that only static arguments can be supplied. This makes the use of using a View to generate the available options limited, as in most cases you want to send context-aware arguments to Views.

It should thus be possible to supply dynamic arguments to a View.

Proposed resolution

Allow the use of tokens when sending arguments to the View.

Remaining tasks

User interface changes

Users can use tokens when defining the arguments to send to a View, when they choose to use a View to generate the available options for an entity reference field.

API changes

None.

Same issue for Drupal 8: #1699378: Allow tokens in entity reference views selection arguments

Original report by @Volx

When using a view for entity selection, it is sometime helpful to have the id of the current entity available in the view. As far as I can see I can only pass static arguments in the field settings.

I added a setting "Pass entity ID" to the field settings form and changed the EntityReference_SelectionHandler_Views so it passes the entity's id to the view as the first argument. For backwards compatibilty the default is to not pass the entity id. Another approach could be to allow using tokens in the arguments field setting, that might already possible in which case consider this issue as a support request :)

CommentFileSizeAuthor
#175 entityreference-use-tokens-2010898-175.patch5.01 KBkarlshea
#172 interdiff-2010898-82-172.txt1.26 KBkarlshea
#172 entityreference-use-tokens-2010898-172.patch5.29 KBkarlshea
#158 entityreference-use-tokens-2010898-158.patch6.14 KBsarvab
#132 related_articles_by_tag.txt3.86 KBnithinkolekar
#126 entityreference-use-tokens-2010898-126.patch5.92 KBdaro.pl
#123 entityreference-2010898-122-Use-tokens.patch5.86 KBdaro.pl
#121 entityreference-2010898-121-Use-tokens.patch5.8 KBdaro.pl
#114 entityreference-2010898-114-Use-tokens.patch5.69 KBhaggins
#112 entityreference-2010898-112-Use-tokens.patch5.44 KBhaggins
#82 entityreference-2010898-80-Use-tokens.patch5.38 KBgeek-merlin
#82 entityreference-2010898-80-interdiff.txt1.33 KBgeek-merlin
#81 entity_reference_view_test-7.x-1.3.zip5.96 KBnithinkolekar
#75 #testing-setup-2010898.png83.26 KBnithinkolekar
#69 #test-article(2010898#65).png46.5 KBnithinkolekar
#66 #6-node-viewed.png58.9 KBnithinkolekar
#66 #5-entityreference-views-selection-token-argument.png114.3 KBnithinkolekar
#66 #4-feature-creation.png94.5 KBnithinkolekar
#66 #3-books-content-type.png36.72 KBnithinkolekar
#66 #2-favorite-content-type.png39.65 KBnithinkolekar
#66 #1-entityform-type.png33.92 KBnithinkolekar
#66 entity_reference_view_test(updated2)-7.x-1.2.zip6.27 KBnithinkolekar
#63 #1-entity_reference_view_test.png40.75 KBnithinkolekar
#63 entity_reference_view_test(updated)-7.x-1.1.zip5.82 KBnithinkolekar
#62 incomplete_feature.png37.95 KBapmsooner
#60 entity_reference_view_test-7.x-1.0.zip3.79 KBnithinkolekar
#58 er_filtered.png72.01 KBapmsooner
#58 er_token_settings.png28.28 KBapmsooner
#53 entityreference-2010898-52-53-interdiff.txt1.07 KBgeek-merlin
#53 entityreference-2010898-53-Use-tokens.patch5.6 KBgeek-merlin
#52 entityreference-2010898-26-52-interdiff.txt3.71 KBgeek-merlin
#52 entityreference-2010898-52-Use-tokens.patch5.6 KBgeek-merlin
#51 entityreference-2010898-26-51-interdiff.txt3.75 KBgeek-merlin
#51 entityreference-2010898-51-Use-tokens.patch5.69 KBgeek-merlin
#50 entityreference-2010898-26-50-interdiff.txt2.04 KBgeek-merlin
#50 entityreference-2010898-50-Use-tokens.patch6.42 KBgeek-merlin
#41 02-token-as-parameter-er-field-inside-entityform.png173.03 KBnithinkolekar
#41 01-token-as-parameter-er-field-inside-node.png173.63 KBnithinkolekar
#33 1.node-field-missing.png52.45 KBnithinkolekar
#33 2.node-tokens-available.png72.04 KBnithinkolekar
#26 entityreference-tokens-as-view-arguments-2010898-26.patch5.65 KBMazzhe
#19 entityreference-tokens-as-view-arguments-2010898-19.patch5.65 KBk.skarlatos
#18 entityreference-tokens-as-view-arguments-2010898-15.patch5.65 KBk.skarlatos
#15 entityreference-tokens-as-view-arguments-2010898-15.patch5.65 KBk.skarlatos
#12 entityreference-tokens-as-view-arguments-2010898-11.patch5.62 KBaoturoa
#10 view-argument-as-token-1699378-46.patch5.6 KBmegachriz
#7 entityreference.code_.2010898-7.patch4.15 KBgeek-merlin
#6 entityreference.code_.2010898-6.patch4.14 KBgeek-merlin
#5 entityreference.code_.2010898-5.patch4.1 KBgeek-merlin
#4 entityreference.code_.2010898-4.patch4.02 KBgeek-merlin
entityreference-pass_entity_view.patch3.98 KBVolx

Comments

Status: Needs review » Needs work

The last submitted patch, entityreference-pass_entity_view.patch, failed testing.

Volx’s picture

Status: Needs work » Needs review
geek-merlin’s picture

geek-merlin’s picture

StatusFileSize
new4.02 KB

Yes, at first i thought "Entity NID is enough for everyone" (tm). After an hour of fiddling with real world problems i realized it hurts.

Implementing token support was so easy with your (very well-written!!) patch laying the ground.

So here's the token support patch flying in. Please have fun, test, review and let's get this finally in!

geek-merlin’s picture

StatusFileSize
new4.1 KB

Improved patch with longer textfield for token verbosity.

geek-merlin’s picture

StatusFileSize
new4.14 KB

Improved patch does not produce token zomies.

geek-merlin’s picture

Title: Pass entity id to view for entity selection » Use tokens for entity selection view arguments
StatusFileSize
new4.15 KB

And avoids empty arguments, views chokes on them.

megachriz’s picture

This has been requested before. At some point it was decided that this new feature must be added to Drupal 8 first, and now its burried somewhere in the Drupal core issue queue:
#1699378: Allow tokens in entity reference views selection arguments

Not sure if I should close this issue as a duplicate though.

jaydarnell’s picture

Doesn't seem like a duplicate to me seeing as #1699378 is for Drupal 8 but maybe I'm missing something.

megachriz’s picture

StatusFileSize
new5.6 KB

@CopperBot
See comment #66 in #1699378-66: Allow tokens in entity reference views selection arguments.

I will repost the patch here that was RTBC there as I'm not sure what the policy is of closing duplicates when the original issue moved to an other issue queue.

megachriz’s picture

Issue summary: View changes

Updated until comment #10. Added a reference to the same issue for Drupal 8.

aoturoa’s picture

#10 works pretty good. Thanks.
I added an array_filter() before returning the $args.
This will support the 'Display all results for the specified field' option in Views core when the filter value is NOT available. An empty string I also consider as NOT available.

aoturoa’s picture

bsarchive’s picture

#12 seems to work for me, in the recently updated version of entityreference (7.x-1.1).

Please can we get this committed? Now every time entityreference is updated, my site breaks, without this patch!

kolier’s picture

#12 works for me as well. Thanks.

k.skarlatos’s picture

patch on #11 works fine for me. The problem is that the textfield has a small maxlength (128) that causes problems when using many tokens, so i changed the patch setting that to 512. I believe this is ready to be committed.

Status: Needs review » Needs work

The last submitted patch, 15: entityreference-tokens-as-view-arguments-2010898-15.patch, failed testing.

The last submitted patch, 15: entityreference-tokens-as-view-arguments-2010898-15.patch, failed testing.

k.skarlatos’s picture

fixed a small syntax error with the above patch. it should be ok now

k.skarlatos’s picture

StatusFileSize
new5.65 KB

sorry for spam, this is the correct patch (hopefully)

k.skarlatos’s picture

Status: Needs work » Needs review
k.skarlatos’s picture

genjohnson’s picture

The patch in #19 works for me. Thanks.

alain dg’s picture

Nice to see a patch! Thx.
But I cannot get this to work after different configs of views.

SCENARIO
I want my ER view to display only nodes that share the same taxonomy term with the edited node.
-> I want a match player field to display a list of players sharing the same season (taxonomy term).
Match Content type:
- season field: 2013 (taxonomy term)
- player field: ER view listing only players inscribed in 2013 (multiple value)
Player Content type:
- season field: 2013 (taxonomy term)

CONFIGS
1/ In the Match content type, for its Player ER field field, I set [node:field-season] as argument of the view.
2/ In Views, I make a list of players with contextual filter
- context filter: has taxonomy term ID
When filter is not available
- default value: taxonomy term ID from URL,
- Load default filter from node page
- Limit terms by vocabulary: Seasons
- Filter to items that share any term
When filter is available
- Specify validation criteria: taxonomy: Seasons
- Filter Value type: Term Ids separarted by , or +

Of course, it works in Views UI by supplying a filter value.

Thanks in advance!

PS: My version of Entity Reference is 7.x-1.0-rc5

Yuri’s picture

With the patch, I still can't get it to work, the ER field just doesn't show the filtered results.
I'm using [node:og_group_ref] as token in the ER field, in order to filter nodes that are part of the same group.
I tried with different versions of ER including the latest dev.

guillaumev’s picture

I just tested this patch and it's working perfectly fine on my side.

Mazzhe’s picture

On my site, the token list lead to memory issues...
I changed the line 49 of patch #19 from
'#theme' => 'token_tree',
to
'#theme' => 'token_tree_link',
and now, it works, with a link to the token table.
Thanks a lot for this patch.

Mazzhe’s picture

roball’s picture

The Viewfield module has this feature already, but it would be nice to have this in Entity reference.

drupalninja99’s picture

I see tokens but I don't see entity tokens, am I doing something wrong?

jpstrikesback’s picture

jpstrikesback’s picture

nithinkolekar’s picture

Entity tokens are not available when ER is inside field collection.I think patch still not working with Field Collection.
Apologies :( this is not only related to filed collection but with basic field also.
Node field tokens like [node:author],[node:field_tags] etc are not available when trying to set view's parameter, but available in Automatic title generation settings(screenshot2).While I am not able to attach file, see next comment for screenshot.

Installed Modules related to token
Token 7.x-1.5
Entity tokens 7.x-1.3
File (Field) Paths 7.x-1.0-beta4

nithinkolekar’s picture

StatusFileSize
new72.04 KB
new52.45 KB

screenshots for #32

nithinkolekar’s picture

@Weblights for #23
I don't know the default behaviour of parameter passing ie whether
view accepts term(s) from external module and convert them to id
or
external module should convert( in this case entity reference) to id before passing it to view.

I came through this same problem(?) and to solve this, in contextual filter config instead of Term Ids separarted by , or + use "Term name converted to Term ID".

nithinkolekar’s picture

This feature is not usable when creating new entity thus making it limited.

For ex.

When creating new Entity for content type TechBooks and this is not actual requirement but for just example.

Title - Beginning PHP and PostgreSQL E-Commerce: From Novice to Professional
TechTags- Autocomplete or checkbox depends on no of terms (Php, Apache, Python etc. all are taxonomy terms)
Similar Books - Autocomplete
--|-----Entity reference using views (We can't pass TechTags value ie [node:field_techtags] as parameter to views while creating, as this TechTags value is not saved yet but when editing value could be passed!)

mustanggb’s picture

The issue I am having with #26 is that tokens work (in my case [node:field-example:nid]), but they aren't being shown in the token browser so it's just guess work what to use.

Is this the same thing you're describing nithinkolekar?

nithinkolekar’s picture

Yes thats what I am getting and for time being just copying token from Auto title generation configuration manually.

As you can see in screenshots from #33, 01 token browser is popup and 02 is the default one without popup.I thing token tree generation methods(if there are any) might be the cause.

roball’s picture

Status: Needs review » Needs work

I think the status of this issue needs to be updated.

geek-merlin’s picture

+++ b/plugins/selection/EntityReference_SelectionHandler_Views.class.php
@@ -164,6 +192,36 @@ class EntityReference_SelectionHandler_Views implements EntityReference_Selectio
+    // Check if the entity has an ID. If not, don't pass the entity to token_replace().
+    if ($this->entity) {
+      list($id, $vid, $bundle) = entity_extract_ids($this->instance['entity_type'], $this->entity);
+      if (!empty($id)) {
+        // Only pass the entity to token_replace() if it has a valid ID.
+        $data = array($this->entity_type_token => $this->entity);
+      }
+    }
+    // Replace tokens for each argument.

Do we really need this? This kills important use cases and the 8.x patch over at #1699378: Allow tokens in entity reference views selection arguments does not have this restriction.

nithinkolekar’s picture

Code
+ if ($this->entity) {
is failing ,thus $data variable is not setting and token replace failed.Taxonomy term field [node:filed_tags] is used as token to get node as entity reference.
Applied patch #26

Modules info
Token 7.x-1.5 - enabled
Entity API 7.x-1.3 - enabled
Entity Token 7.x-1.3 - disabled
Entity Reference 7.x-1.1+3-dev - enabled

nithinkolekar’s picture

dpm($this->field['settings']['handler_settings']['view']['args'])
is showing correct token ie [node:field-parameter] but it is not replacing with value. see screenshots of other dpms.

update:
inserted if statement in protected function __construct($field, $instance, $entity_type, $entity) like

if($entity)
$this->entity = $entity;
else {
dpm("entity not set");
}

but if statement fails here too.any clue on this?

megachriz’s picture

@axel.rutz, #39
Sorry, I put that piece of code in. The reason why I added that check for an existing entity was that - in case of nodes - some properties of the node are not yet available on the node add form. In my case this resulted into errors, because I used the [node:nid] token. See #1699378-43: Allow tokens in entity reference views selection arguments for background information.
I agree the restriction for existing entities should be eliminated, but at the same time no errors should be shown when a token is used for a property that isn't yet available.

geek-merlin’s picture

@#42:
i agree that [node:nid] should be empty or 0 for new nodes, not creating errors.
so we might simply set it's id to 0 in that case (i prefer 0 as i remember that views in d7 sometimes chokes on empty arguments)

antoinetooley’s picture

Hi, I have used this patch in drupal 7, so I can give my reference view an argument with tokens and I think it is working. But I really want to grab the og_group_ref parameter in my url added by the entity reference prepopulate module and place this as my argument in views. The url of the node add page would be something like this: http://localhost/example/node/add/example&og_group_ref=171.
Would anyone be able to help me as to which token I could use I am guessing from the current_page section to get this value. I have tried a few things but nothing seems to be working.
Thanks in advance.
Antoine

nithinkolekar’s picture

Also tried with AET like

[aet:node:1:field_tags]

where 1 is the node id which is succeeded, but nid is not dynamic :(.

So tried another token after applying patch https://drupal.org/node/2082269#comment-7829711

[aet:node:[current-page:url:args:1]:field_tags]

but this is not replacing token with actual value.

I can confirm this patch doesn't work when entityreference field is inside EntityForm. Also raised the issue node related tokens are not available/accessible to entityform module

smurfxx’s picture

#26 is working, I hope this will be implemented in the future release of this module!

nithinkolekar’s picture

I have created another thread and patch for my specific issue i.e when node tokens were not available to entityreference which is inside entityform

pass nid to entity selection view via autcomplete path - when node tokens are not available

dobe’s picture

#26 worked for me.

apmsooner’s picture

#26 worked for me also and my case is quite unique.
Field Collection
- Entity Reference #1 (node)
- Entity Reference #2 (field collection related to node from entity reference #1). This entity reference is filtered by a view with contextual filter of nid from #1. The entity reference field passes the token [field_collection_item:field-ingredient-ref:nid] from #1 to the view.

The only challenge was finding the token to use as it doesn't show up in the token browser but once i figured that part out, works fabulous.

geek-merlin’s picture

Status: Needs work » Needs review
StatusFileSize
new6.42 KB
new2.04 KB

Hmm, noone did it? Let's squash this down.
#26 has been RTBC but has issues:
* a) #29..33: entity tokens not showing up
* b) #35..43: new entities should be handled gracefully

This patch improves #26 but only addresses b). Still setting to NR to bug the testbot.

geek-merlin’s picture

This one should handle a) and b).
Some notes:
* i think we can safely use $entity_info['token type'] as this is what auto_entitylabel does too
* tested that entity tokens now show up in the browser
* did *not* test token handling for new entities (you may PM me if this still fails so we can finally make this RTBC)

geek-merlin’s picture

StatusFileSize
new5.6 KB
new3.71 KB

Urps, forgot one cleanup line.

geek-merlin’s picture

StatusFileSize
new5.6 KB
new1.07 KB

OK... revision key can be an empty string and should be ignored then. Fixed.

The last submitted patch, 51: entityreference-2010898-51-Use-tokens.patch, failed testing.

The last submitted patch, 52: entityreference-2010898-52-Use-tokens.patch, failed testing.

geek-merlin’s picture

OK lights are green, so we now need a manual tester to set #53 RTBC. Anyone?

apmsooner’s picture

Status: Needs review » Reviewed & tested by the community

I tested patch #53 on 7.x-1.1. Works perfect for me using entity reference to field collection items. All relevant tokens available for selection and field is filtered to token as described.

apmsooner’s picture

StatusFileSize
new28.28 KB
new72.01 KB

Here are some screenshots to depict my setup. I'm using the functionality in a field collection (recipe ingredients) that references a node (ingredient) which filters field collections (weights) that relate to node (ingredient).

The last submitted patch, 18: entityreference-tokens-as-view-arguments-2010898-15.patch, failed testing.

nithinkolekar’s picture

StatusFileSize
new3.79 KB

@axel.rutz
still not working for my specific setup #41. more details about setup https://www.drupal.org/node/2244987

Attaching a basic setup(more info) bundled into feature with Article content type and entityform for testing

apmsooner’s picture

@nithinolekar,

I've read through your issues... but having a hard time understanding what the goal is here. Can you dumb this down a little to explain what exactly you are trying to achieve? And what exactly isn't working? The token you need isn't available from the browse tokens dialog or it is but simply not working?

apmsooner’s picture

StatusFileSize
new37.95 KB

@nithinolekar, your feature doesn't have any fields associated with it (see attached). Without a better explanation of what the goal is and/or proper feature setup to test, I don't think this issue should hold up the progression of the patch being included in the next release. It sounds more like a configuration issue on the view or an entityform specific issue.

nithinkolekar’s picture

@apmsooner
that feature was created long back when I haven't had experience with Features module :(.

Recreated feature and attached.

It sounds more like a configuration issue on the view or an entityform specific issue

couldn't figure which module is causing this as different modules are involved in the setup likely entity api, tokens, entity reference,entityform and views. As for the views is concerned I doubt about misconfiguration because it is simple view with entityreference as display and taxonomy term id as contextual filter.

About setup:
It is like asking site user to submit their favorite book but category wise like
Favorite php book
Favorite drupal book etc.

For this simple setup, entityform is created which has entityreference field refer to Node of content type Books.This books content type has tag associated to which views contextual filter should apply.

Another content type is created called Favorite to which entityform is attached and this content also has another term reference field called Parameter which should be passed as argument to views to extract book which having the same tag(s) only.

In my setup as u can notice field Parameter is presaved before submiting EntityForm and hence "new entities" problem will not raise in this scenario.

Finally how to test?

create some nodes of type books which has some tags like
php
drupal
mysql

create a node of type Favorite with
1. title : Favorite php book
2. parameter : php
3. book form : select entityform created

When new node Favorite php book is viewed then user can see entityform (set rendered entity via manage display) and test by filling field "Book Name".

apmsooner’s picture

@nithinolekar,

Your feature is still incomplete as it doesn't include the content type "Favorite" that you are referring to. There are no term reference fields attached to the books node nor the entityform type. Trying to give you the benefit of the doubt and help you but your uncertainty in your own issue being applicable to the actual thread:

couldn't figure which module is causing this as different modules are involved in the setup likely entity api, tokens, entity reference,entityform and views. As for the views is concerned I doubt about misconfiguration because it is simple view with entityreference as display and taxonomy term id as contextual filter.

... as well as the lack of accurate feature setup to even test it out for you is really potentially hijacking the progress of the patch that I myself have tested and confirmed working with proper configuration. The only advice i can offer is to perhaps manually pass term ids into the views ui preview field to see if you can obtain desired result and then backtrack through your settings elsewhere.

apmsooner’s picture

StatusFileSize
new44.54 KB

FYI,

To do what i think you are trying to do, you can use this token in the entityform's entity reference field:
[current-page:url:args]

Assuming the entityform is referenced to the node and rendered to display as form, you should see something like the attached screenshot.

Note: Your entity reference view needs to be of type "term", not content. You can import the attached sample view to see configuration and adapt to your needs. Just to confirm... the token approach I mentioned works as designed as it just grabs the nid argument from the page and passes it to the view.

View:

$view = new view();
$view->name = 'book_tags';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Book tags';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Taxonomy term: Content using Tags */
$handler->display->display_options['relationships']['reverse_field_tags_node']['id'] = 'reverse_field_tags_node';
$handler->display->display_options['relationships']['reverse_field_tags_node']['table'] = 'taxonomy_term_data';
$handler->display->display_options['relationships']['reverse_field_tags_node']['field'] = 'reverse_field_tags_node';
$handler->display->display_options['relationships']['reverse_field_tags_node']['required'] = TRUE;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['relationship'] = 'reverse_field_tags_node';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';

/* Display: Entity Reference */
$handler = $view->new_display('entityreference', 'Entity Reference', 'entityreference_1');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'entityreference_style';
$handler->display->display_options['style_options']['search_fields'] = array(
'name' => 'name',
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'entityreference_fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;

nithinkolekar’s picture

StatusFileSize
new6.27 KB
new33.92 KB
new39.65 KB
new36.72 KB
new94.5 KB
new114.3 KB
new58.9 KB

@apmsooner

thanks for your sincere help

I hope this time feature will wok, as I tested it by importing to other fresh drupal installation on local system.Also attaching the each configuration screenshot.

The only advice i can offer is to perhaps manually pass term ids into the views ui preview field to see if you can obtain desired result

I checked it by passing term id directly which is working fine but when token is used like [node:field-parameter] then it is not replacing with value(in the above case term php).

The main idea about this setup and requiring the token support is , we can use same form for collecting different submissions with each different node like.
Favorite php book - (which could have term php and passed as argument).
Best Drupal 7 module - (which could have term drupal7 and passed as argument).

For time being I am using patch pass nid to entity selection view via autcomplete path - when node tokens are not available but would prefer token method.

nithinkolekar’s picture

@apmsooner for #65 I will test it soon..

apmsooner’s picture

I think #65 satisfies the functionality but i didn't account for the multiple content types involved or really understand the need.... Maybe consider simplifying the workflow or browse manually the tokens at the node level @ /admin/help/token and see if you can drill down to what you need for the nid to pass to the view. Either way, a view of type content i don't think would ever satisfy what you're trying to do if you are trying to return 'terms' and your displaying content title in the view.

nithinkolekar’s picture

StatusFileSize
new46.5 KB

@apmsooner

test #65 with tags like
[current-page:url:args] : doen't work, not an issue.
[current-page:url:arg:1] : worked
[node:id] : this also worked

but only when widget is set to Check boxes/radio buttons or select list.

It doesn't work for auto complete widget(see screenshot).Also this comment from Clive on SO is informative about autocomplete path.

howards’s picture

Cleanly applied the patch in #53 against 7.x-1.x commit dc4196b4. It works!

schifazl’s picture

This patch works flawlessly on my site, thanks! :)

geek-merlin’s picture

@nithinkolekar / @apmsooner
it looks like you did an impressing debugging / support job, and to be honest, i don't get every detail of that debugging.

what i thin i got ist:
there are still issues with autocomplete widget.
but this patch did not break anything that worked before, so i suggest to have it committed and do the rest in a separate issue.
(feel free to correct if that is not correct)

apmsooner’s picture

@axel.rutz,

The autocomplete issue has nothing to do with this new code but rather a configuration issue in his entity reference setup. I think we've narrowed down all the issues brought by nithinkolekar to configuration outside the scope of what this patch does. It works perfect for everyone else that has tested under proper configuration so i say... all lights remain green to move forward as you suggest.

nithinkolekar’s picture

@axel.rutz / @apmsooner

Whole setup is configured for testing in one of my unused/testing domain. Will PM admin login details if you are interested and you can view as anonymous also.

Modules -
Drupal core 7.31
Entity Reference 7.x-1.1+3-dev (applied patch #52)
Token 7.x-1.5+4-dev
Views 7.x-3.7+35-dev
Entityforms 7.x-2.0-beta4+1-dev

No other patches are applied to any other modules.

nithinkolekar’s picture

StatusFileSize
new83.26 KB

attached missing screenshot..

apmsooner’s picture

Autocomplete works fine for me in my testing even though i'm not sure why anyone would want to use that over select list when the values are being filtered to limit results. That just doesn't sound too user friendly to me even in your case @nithinkolekar. Nonetheless, if you're not seeing results, you may need to adjust the entity reference view settings to define the fields that are searchable and also maybe adjust the entity reference field settings to "starts with" instead of "contains" for testing purposes.

@nithinkolekar, I still don't see this being an issue related to the patch here so please research further on your end and/or poise the issue to another thread outside this one.

nithinkolekar’s picture

why anyone would want to use that over select list when the values are being filtered to limit results

values are filtered based on terms, but it might be possible that no of nodes having that term is huge for select list to render.

you may need to adjust the entity reference view settings to define the fields that are searchable and also maybe adjust the entity reference field settings to "starts with" instead of "contains" for testing purposes.

views is returning values for both "starts with" and "contains" when token argument left blank but doesn't work when provided.

Autocomplete works fine for me in my testing

any info about setup which involves Autocomplete will be helpful , so that I can compare with my setup.

apmsooner’s picture

@nithinkolekar, sorry but i can't spend anymore time helping you on something that i don't believe is affected by the patch. The complexity in your use case is not typical for the general needs of this patch thus I would advise you to setup a much simpler implementation of basic autocomplete functionality and start narrowing down to find potential issue instead of assuming this patch is a problem.

geek-merlin’s picture

@nithinkolekar: although @apmsooner did a great job assisting you, it is a problem if an issue like this has lots of noise not directly related to its core (and you usually get harsh comments for "hijacking").
You should open a separate support issue or use forum or IRC (in addition to simplification as suggested!).

So to summarize: RTBC as to #53 / #57 / #73.

geek-merlin’s picture

Status: Reviewed & tested by the community » Needs work
nithinkolekar’s picture

StatusFileSize
new5.96 KB

@axel.rutz

@apmsooner's main complain is about my setup which involves lot of modules and looks complicated at first glance. So I came up with simplified setup which involves only single content type and comment field setup.
As for the entity reference there are multiple widgets available which includes select list, checkbox and auto complete widget by drupal core.

...you usually get harsh comments for "hijacking"

My issue about this patch is, it is partially working with select list and checkbox only. I still couldn't find whether it is a problem with autocomplete widget as you mentioned in #72 (if it is then will create a new issue there).

Setup
1. Create some contents of type Articles content type with similar tags
2. Add a new entityreference field to article content type's comment field which should have views as entity selection and [ node:field_tags ] as View arguments.
3. create a usual view with display : Entity Reference list and contectual filter: Content: Has taxonomy term ID
you can test the setup @
http://ps2html dot org/2010898/node/7
also attaching the feature of this setup.

If you think it is still not convincing you then I hope some one else will explain more clearly than me in the future when he/she will came through the same problem :).

geek-merlin’s picture

Status: Needs work » Needs review
StatusFileSize
new1.33 KB
new5.38 KB

OK here's the patch with the array_filter changed, see #80.

geek-merlin’s picture

@#81: Please do not get me wrong, i'm appreciating all input and now i understand the issue you are raising.

But as the ViewsSelection code is completely widget agnostic i can not see the issue with the autocomplete widget can be solved here.
Now that you distilled a minimal failing case please file that as a separate bug with link to this issue (maybe after testing with the current re-roll ;-).

nithinkolekar’s picture

@axel.rutz

Sure, will create issue once this patch gets committed.

nithinkolekar’s picture

Now I am testing with select list/checkbox only as @axel's info about autocomplete.

some clarification needed about this patch

Is it mandatory to have both agrument field(token) and entityreference(which accepts token as filter) should be in the same bundle/entity.
As in my case mentioned in @81 argument field is on node entity and entityreference is on comment entity.

I had done a mistake in the views contextual filter by setting Load default filter from node page, that's good for related taxonomy blocks to true. This makes view collecting term data from node page although token value is not available to view at all.When this option is disabled then I came to know that token replacement is not actually happening.

ex: if token value is [ node: field_tag ] which is a node token, then line
$data[$info['token type']] = $entity;
makes $data['comment'] = < comment object > and hence

$args[$key] = token_replace($arg, $data, $options);
is failing to replace token.

Am I correct about this?. I request to all others who claimed that this patch is working at their side, could share about their setup if possible.

plong0’s picture

Great to see this issue is being actively addressed!
I am using the patch from #53, and trying to do following:

I have a "Report" content type with these fields:
field_client - Entity Reference using a view for nodes of type "Client"
field_contact - Entity Reference using a view for nodes of type "Contact" and with contextual argument for the nid of the field_client

What I would like is when I select a value for Report's field_client, the field_contact shows the Contacts for the selected Client.

I hope the explanation makes sense.

I have tried to set it up with the field_contact's view arguments to use the token [node:field-client:nid]
I have tested the view with a client id as an argument, and it does show the Contacts as expected - just having trouble getting those results into my entity selection list.

Edit:
After saving the node with a value in field_client, on the node edit page the field_contact list shows the correct contacts - until I change the field_client to a different value (it keeps the same token value it had when the page loaded)

Is there a way for tokens to be provided dynamically when a field is changed on a node form?

plong0’s picture

Not sure if it is by design, but with patch #53, I am receiving the error:
Notice: Undefined property: entityreference_plugin_display::$id_field_alias in entityreference_plugin_style->render() (line 49 of /webroot/sites/all/modules/entityreference/views/entityreference_plugin_style.inc).

The error shows up on the edit field page and on the add node page.

The error only appears when the enttity reference view contextual filter's "no value" handler is set to any of the bottom 3 ("Display ...") settings.
The error is not present when using the top 3 ("Show All", "Provide Default", "Hide View" settings.

Thought I would share this in case anyone else experiences that error.

schifazl’s picture

plong0 about #86 I agree with you that this is an important functionality. In the meantime you can try the Reference Option Limit module, but it's a bit limited. Being able to do this with tokens and views would be marvellous

plong0’s picture

I guess what it comes down to is tokens being updated and applied in real-time. Almost seems like there would need to be a "token changed" js behaviour so that modules like this one can be notified about fresh token values in real-time.

And thanks schifazl I will give the Reference Option Limit module a try.

hansfn’s picture

I ended up using a completely new module - DFV - Dependend Field Values - which seems to work very well.

PS! Read this issue if you need checkboxes.

plong0’s picture

Tried out both those modules. Seems like DFV would be a lot more powerful (since it uses views), while Option Limit Module is a lot more compact/simpler.

The problem I have with either one is that they don't seem to work with an Inline Entity Form. Going to raise that issue on both and see who can help first.

Cheers, thanks for the direction on this.

geek-merlin’s picture

Please folks do not hijack this issue. it's about getting a patch in.

We still need test of #82

schifazl’s picture

Well, I'm testing #82 (with a select list) and everything works smoothly for now. I didn't do any complicated view though, just simple filtering

geek-merlin’s picture

@schifazi #82: did you use tokens? if yes please set status to RTBC.
as the patched component does not know anything about the used widget nor the view but is only about providing token placeholders, testing the tokens work is the main point.

nithinkolekar’s picture

hi alex,
another setup for testing this patch which worked for user object token [ current-user:uid ] and surprisingly this worked for autocomplete too!

1. add entityreference field "my_other_article" to content type Articles and set it to views selection with argument [ current-user:uid ]

2 create a view of nodes of content type articles with contextual filter settings
Content: Author uid
When the filter value is NOT available - Hide view

3 create at least one article node with each different user.This is just to test whether token is passing properly or not.

4 try creating second article by filling my_other_article(ER field) which would work perfectly by passing token as argument. This is also working with autocomplete too.

Only mystery remains is , why it isn't working for node tokens?

update: this is tested with #82 patch.

schifazl’s picture

Status: Needs review » Reviewed & tested by the community

Setting status to RTBC. Yes Axel, I'm using tokens (specifically [current-page:query:field_name]).

I've tried to change the widget type. It works both with select and option, but not with autocomplete and autocomplete (tag style).

apmsooner’s picture

I think autocomplete issues "could" be related to the view configuration in defining searchable fields in the settings. I know after tweaking that, my autocomplete testing worked when it didn't initially. I can't recall exactly what i changed unfortunately....

schifazl’s picture

I can't find these settings, I've checked all the view's settings

apmsooner’s picture

@schifazl,

if you've added a display to your view of type "Entity Reference", you would go to the settings link in the format section of the view ui. Click that and you'll see checkboxes for search fields.

schifazl’s picture

Ah OK, sorry for the misunderstanding. I already checked that when I have created the view, otherwise I couldn't even save it.

schifazl’s picture

I was so taken with designing my site that I didn't notices a warning, but before setting status to needs work I'm asking if this is just a problem of mine:

When creating a new node which has a field with a view vith tokens as arguments I get this warning:

Notice: Undefined property: stdClass::$nid in node_tokens() (line 112 of modules/node/node.tokens.inc).

It's only me?

liquidcms’s picture

Status: Reviewed & tested by the community » Needs work

as far as i can tell this still does not work for autocomplete or any other widget

hard to tell from token text what the correct token is they say url:args but example suggests url:arg i tried both of these:
[current-page:url:args:1]
[current-page:url:arg:1]

and then possibly the question is how to set up the contextual filter on the view. i tried numerous options but it should be something that allows the view preview to work i would guess, so i have:
When the filter value is NOT available: User ID from URL
When the filter value IS available or a default is provided: nothing set
with this views preview give me the correct list.

nothing i type in my autocomplete field returns any results. switching to select list and i also have no results.

my set up is a field on user profile. the field is a list of nodes which the user is tagged via user reference like field.

i have latest -dev patched with: entityreference-2010898-80-Use-tokens.patch

before i patched i was able to get some list of nodes in my autocomplete but only if i change the view to simply list all the nodes.. i.e. basically dont use the contextual filter.

liquidcms’s picture

perhaps my issue is a different issue than here although i think this is a way people are trying to fix underlying issue: views with contextual filters dont work with entity ref selector. technically i dont need to pass an argument; if the entityref uses the view as it is defined which is to simply pull the uid from url when no arg is available.

liquidcms’s picture

nope, my bad.. not sure what i have set up different now but the select list and checkbox widgets do work (not passing arguments as i don't require that); but autocomplete doesn't work.. separate issue i suspect.

actually i went back to 7.x-1.1 and my entity selection with views works fine with checkboxes or select list for 2 reasons (likely obvious to those that have been working this issue since it was started):

1. my view doesnt require any arguments to be passed as it is set to pull args from url
2. these 2 widgets are not ajax based and the ajax calls mess up the url losing my uid/nid from being able to be passed to the view arg handler

liquidcms’s picture

so this is simple enough, the only reason autocomplete doesnt work for url based contextual filters is because the url tokens dont work within ajax calls.

the following code creates a token based on the HTTP_REFERER which is the originating path prior to the ajax call:

/**
* lets create a URL token based on HTTP_REFERER so that it can be used with ajax based autocomplete calls like we need for
* EntityReference selector to pass url args to a View
* 
*/
function liquid_token_info() {
  $info['tokens']['current-page']['referer:arg:n'] = array(
    'name' => t('REFERER based URL Args'),
    'description' => t('URL Args based off HTTP_REFERER (AJAX happy).'),
  );
  return $info;
}

function liquid_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $referer = $_SERVER['HTTP_REFERER'];
  $parts = parse_url($referer);
  $path = explode('/', $parts['path']);
  array_shift($path);
  foreach ($tokens as $name => $original) {
    $bits = explode(':', $name);
    if ($bits[0] . ':' . $bits[1] . ':' == substr($name, 0, 12)) {
      $position = $bits[2];
      $replacements[$original] = $path[$position];
    }
  }
  return $replacements;
}

so adding a token of [current-page:referer:arg:1] fixes my view and autocomplete works as expected.

geek-merlin’s picture

Status: Needs work » Reviewed & tested by the community

So setting to RTBC as of #96.

Again: this patch is widget agnostic and widget issues should get their own issue to not noise this one dead. Thanks!

The findings e.g. from #105 are very valuable but should live in their own crosslinked issue

apmsooner’s picture

@axel.rutz,

#105 might be related to an issue i'm coming up with that ultimately affects this patch from being effective when there is another field that has unlimited values thus added via ajax. I'm seeing an issue after adding 3 or 4 values of an unlimited field results in an "An illegal choice has been detected." error and upon saving i'm noticing the entity reference fields are reset with nothing to choose from... I'm concerned the underlying issue might wrongfully get associated with this patch and wondering if you had come across this and had any ideas?

Note: the issue ONLY happens if a value is selected from entity reference field and then adding values to unlimited field. The error pops up after the 2nd added value usually and prevents further values from being added. If the entity reference field is empty, the widget works fine and no errors. I really hope #105 is considered in this review....

apmsooner’s picture

Okay sorry for the crosspost but I'm certain someone else will come across my issue in #107 and think its related to the patch and found a solution here: https://www.drupal.org/node/1818542

Short answer is, in the view settings, set basic validation to show all results if filter isn't found.

schifazl’s picture

What about #101? Am I the only one with that warning?

pontus.froden’s picture

I can also confirm #53 with 7.x-1.1 works great. I also get the same error as #87.

haggins’s picture

Tested #82 and found a flaw:

The view accepts 2 contextual filters. The first one has this setting:
"When the filter value is NOT available: Provide default value (Content ID from URL)"

The second filter comes with this:
"When the filter value is NOT available: Display all results for the specified field"

So the second filter is/should be optional and actually is with the view preview function. However, when I set the argument list of the entityreference field to [current-page:url:args:value:5], [current-page:url:args:value:6] I only get a result when I provide both arguments.

haggins’s picture

Status: Reviewed & tested by the community » Needs review
StatusFileSize
new5.44 KB

The problem is, that this module calls the view always with both arguments whether they have a value or not. So the view interprets the second argument not as "not available" but as empty

I just updated #82 in a way, that arguments which are empty after token_replace() will be removed.

Can you think of any negative side effects of doing this?

I can imagine a option to enable the removal of empty tokens would be handy. What do you think?

Status: Needs review » Needs work

The last submitted patch, 112: entityreference-2010898-112-Use-tokens.patch, failed testing.

haggins’s picture

Status: Needs work » Needs review
StatusFileSize
new5.69 KB
haggins’s picture

Status: Needs review » Reviewed & tested by the community

Sorry for all the confusion guys. #82 is a great patch. For the issue with the optional argument, there is an easy workaround in views itself:

The optional argument filter needs this settings:

When the filter value is NOT available: Display all results for the specified field
When the filter value IS available or a default is provided: Specify validation criteria -> PHP Code:

if (empty($argument)) {
  return FALSE;
}
return TRUE;

Action to take if filter value does not validate: Display all results for the specified field

skadu’s picture

This looks good to me, my token tree browse won't load correctly, leads to a white screen, but the token passing works just fine. Thanks for your work on this everyone.

alphawebgroup’s picture

any chance to commit that patch #114?

biswajeetparida’s picture

is patch #114 works?

alphawebgroup’s picture

sorry for misleading...
i meant #82, not #114

schifazl’s picture

I don't think that a patch which forces to use a workaround in views (as stated in #115) should be accepted. I would propose to test patch #114, if it solves this problem (which I have too). Right now I don't have the time to test it, but in the weekend I will do it.

daro.pl’s picture

After node save I'm getting the following error:

Notice: Undefined index: cleanup in EntityReference_SelectionHandler_Views->validateReferencableEntities() (line 165 of /var/www/tsar/sites/all/modules/entityreference/plugins/selection/EntityReference_SelectionHandler_Views.class.php).

My fixed version of the #114 patch.

Status: Reviewed & tested by the community » Needs work

The last submitted patch, 121: entityreference-2010898-121-Use-tokens.patch, failed testing.

daro.pl’s picture

Fixed my last patch #121 issues.

alphawebgroup’s picture

Status: Needs work » Needs review

Status: Needs review » Needs work

The last submitted patch, 123: entityreference-2010898-122-Use-tokens.patch, failed testing.

daro.pl’s picture

daro.pl’s picture

Status: Needs work » Needs review
geek-merlin’s picture

Status: Needs review » Reviewed & tested by the community

I've taken some time to think about the "#82 vs. #114" question.

#114 did delete all empty arguments to workaround views not taking them as exception values.
It turns out that this approach only makes sense when the argument is the last one.
Filtering out empty "middle" arguments will make later arguments go into slots they are not meant to.
This will kill kittens and cats.

So we should
* fix that problem in views - i created #2398611: Empty exception value not recognized for this
* work on from #82 - which was RTBC as of #96

Thanks again @haggins for your finding in #114. And everyone: I think this is RTBC and other things like the autocomplete issue raised should go into followups. But if you find someserious problem and have to improve this patch, please always add some explanations what was changed and an interdiff to the origin patch. Otherwise we get lost in a total mess...

geek-merlin’s picture

(#53 is dead.)

nithinkolekar’s picture

Status: Reviewed & tested by the community » Needs review

On my previous comments it mentioned that patch doesn't seems work with autocomplete widget and others are agreed with it.Now I am testing with other widget where others claims it is working.

such a long thread and almost forgotten the need of this patch :).

here is the rephrase from OP

User interface changes

Users can use tokens when defining the arguments to send to a View, when they choose to use a View to generate the available options for an entity reference field.

Is this patch work while entity(node) creation ? (i.e while submitting form)
Assuming view is configured properly and tested by passing tid in preview.

field_tags
select list widget
should be passed as token to entityreference field

field_articles
select list widget
Entityreference field
Is it possible to use [node:field_tags] token as parametcer here or
should it be [current-page:query:field_tags] (which is not working)

If yes and if we change the value of field_tags will that trigger the view to render again?(this feature is available in dfv). I know it is not the function of this patch but curious what others are getting who claimed that this patch is working.

geek-merlin’s picture

#130: even after several times reading i do not understand. can you please describe exactly how to reproduce what is not working?

nithinkolekar’s picture

StatusFileSize
new3.86 KB

@axel.rutz

This testing is done with fresh drupal installation and with required contrib modules which are required for this patch.
Steps to reproduce

1. Add some terms to tags taxonomy namely PHP, CSS, Mysql, Drupal

2. Create Content of type articles with tags set any one or more of the above created terms.
ex.
article 1 , tags: css, php
article 2 , tags: php
article 3 , tags: mysql, drupal
article 4 , tags: css, druapl

3. Create a view of content Article having
Display : entity reference
contextual filter : Content: Has taxonomy term ID , Provide default value : Taxonomy term id from url
Test by passing tid it should work fine. (attached the views export code)

4. Add a entityreference field to Article content type having
name : Related Based on tag (field_related_based_on_tag)
widget : select list
Entitly selection : select view created in step 3 , set token parameter [node:field_tags]

5. Change widget type of field Tags in Article to select list (just avoiding autocomplete widget in the whole setup, no other reason)

Now the testing part

Try to create a content of type article this time with additional entityreference field appears and for tags select list appears instead of autocomplete as we changed in step.

Here when tag is selected it should load entityreference select list by passing tag's tid through [node:field_tags] to view right? But it doesn't : (
This function in available in dfv as commented in #90

please share your steps which is working in your setup.

nithinkolekar’s picture

Status: Needs review » Reviewed & tested by the community

For my particular use case using autocomplete widget I found 2 links
1. Excellent article by Bryan where he explains about autocomplete widget/path , why it is not possible and also how we can pass additional arguments to autocomplete widget.

2. Entity Reference View Widget is providing hook to accomplish this task. more info @ #1626668: Provide referencing entity as views argument

Finally switched to Entity Reference View Widget as autocomplete widget alternative and
dfv for other widgets like select list,check box.

Because others are claiming that this patch is working , changing status back to RTBC.

Nithin

OliverColeman’s picture

#126 works for me (brilliant, love it), except that when I set the Remove empty arguments checkbox it doesn't stay set once the form is submitted. The checkbox gets it's default value from the line
$default = !empty($view_settings['cleanup']) ? $view_settings['cleanup'] : 0;
but $view_settings never seems to contain anything other than values for the keys view_name, args and display_name.

Not reverting the status to Needs Review because I haven't tested this in a clean set-up. Does this checkbox work for others?

Update: just noticed that besides the value not being stored in the settings for the field, the checkbox config should be using '#default_value' => $default, rather than '#default' => $default,.

geek-merlin’s picture

Please note that #82 is the current patch and "remove empty arguments" is a different issue and should go into a followup.

howards’s picture

For all those plagued by the autocomplete vs checkboxes/radio issue, it appears there was an issue created a while back #1978274: Entity Selection Using Entity Reference View - Works with Select List But Not with Autocomplete

mustanggb’s picture

Priority: Normal » Major

There is a lot of demand for this feature, so bumping priority to reflect this.

joshua.boltz’s picture

The patch in #82 worked great and added the token functionality into the views argument field from within an entity reference field.

This is a huge improvement and efficiency, and without it there is a lot of duplicated work to handle the various scenarios whereas this patch adds the dynamic aspect to it.

shaisamuel’s picture

I opened #2498755 for the "remove empty arguments", which doesn't function.

sonicthoughts’s picture

Since @shaisamuel pulled out #2498755: Add "Remove empty arguments" checkbox when Views entity selection mode is used - can we please commit this to dev (and hopefully have a release soon:))

mkolar’s picture

Hi, I can't get it to work.. my entityreference field is inside field_collection, I'm using token current url query to but after click to "add another item" to field collection select-boxes are empty (view didnt get correct argument). Otherwise this patch works with select box fields! Looks like this patch works if the field_collection field is not set to unlimited number of values.

apmsooner’s picture

@mkolar, your issue is with ajax call happening on the "add another item" action. The url argument is essentially ignored at that point. I've experienced the same and the only solution I've been able to come up with as workaround is to hide field collection from node form and add field collection items separately and individually outside the node. I believe anything initiating an ajax call will break the entity reference view argument.

geek-merlin’s picture

tchopshop’s picture

Hello, I have this token argument working perfectly on an ECK entity referencing a node, but now I'm using the same entity reference view with a node that references another node. Both nodes are group content and I'm trying to have the entity reference field only select content from the other content type constrained by the group (as I did with the entity). However, the og_group_ref token does not work in this situation. I've tried all combinations, including the same format as the entity that DOES work, i.e. [ENTITY:FIELD:nid]. Also I've tried [ENTITY:FIELD:gid], [ENTITY:FIELD], [ENTITY:FIELD-FIELD], [ENTITY:FIELD_FIELD] (ie. using the machine name with hyphens or with underscores). Nothing works. The token is working in other situations, such as in the path alias. I don't know if this is an organic group issue or a token entity reference issue.

UPDATE: I added a second entity reference field on the node that was not a group reference field and the token from that field worked. So it is an issue with group entity reference field tokens.

schifazl’s picture

The token replacement doesn't work if I'm logged in as administrator, but if I'm logged as normal user everything works. Am I the only one with this issue?

EDIT: Never mind, the problem must lie somewhere else: when a user has the administrator role the fields of the entities instead of being field['und'][0] are just field[0], and probably this is the reason for which the entity metadata wrapper fails loading the field's value. That's odd...

eugene.ilyin’s picture

#126 worked for me.

stiknoltz’s picture

For anyone with the "'Remove empty arguments' checkbox doesn't save" issue documented on #2498755, I've posted a re-roll of #126 in that issue thread that solves.

mustanggb’s picture

Marking as a 7.x-1.2 candidate.

weri’s picture

The patch #126 worked for me too. Thanks!

mustanggb’s picture

Just to reiterate #82 is the patch that is RTBC, the empty exception issue is over in the views queue #2398611: Empty exception value not recognized.

maxplus’s picture

Thanks,
#126 is also working for me!

skylennard’s picture

I discovered this issue while working on a content type entity reference (select list) field, with a views:filter entity selection...

On node create/edit forms, I needed to give an argument to the view filter of the current value of another node field, so it could filter out the option on the select that matched the current value.

I ended up solving this problem super easily inside of my hook_form_alter with one line of code:

unset($form['fieldname'][LANGUAGE_NONE]['#options'][$current_id]);

Thought this might be helpful to someone else?

nwom’s picture

Edit: My comment was not relevant to the functionality of this patch.

junaidpv’s picture

#126 is working good for me too!

joewhitsitt’s picture

#126 worked for me.

nimek’s picture

#126 worked for me.

Collins405’s picture

#126 worked for me as well.

PLEASE can we get this committed? This fixed a huge bug for us here... https://www.drupal.org/node/2752629

When using a View to get the results of an Entity Reference field, after Ajax is run (For example adding a row to field collection), that View will lose its contextual argument, causing no results in the options, and breaking the page.

Using the token [field_collection_item:host:id] as the Views Argument was the fix.

sarvab’s picture

As mentioned in #134, the option to "Remove empty arguments" doesn't work with the latest patch at #126.

Attaching updating patch that fixes usage of that option.

Status: Reviewed & tested by the community » Needs work

The last submitted patch, 158: entityreference-use-tokens-2010898-158.patch, failed testing.

The last submitted patch, 158: entityreference-use-tokens-2010898-158.patch, failed testing.

geek-merlin’s picture

Once again: "Remove empty arguments" is not part of the original issue.
The patch without it was already RTBC and a questionable and unrelated feature now blocks the commit.

joelpittet’s picture

@axel.rutz #126 is not RTBC either. The coding standards needs fixing and it introduces a bug.

+++ b/plugins/selection/EntityReference_SelectionHandler_Views.class.php
@@ -52,13 +53,41 @@ class EntityReference_SelectionHandler_Views implements EntityReference_Selectio
+          '#default' => $default,

Not #default but #default_value which looks to be fixed in #158 and mentioned in #134 too.

I agree on the 'not part of the original issue' part though, and that should probably be removed, keep things simple make and make follow-ups will help get things in.

@sarvab an interdiff could help show your changes between patches, could you put on in on the next patch please?
If you've not before it's just a diff between the previous patch revision(committed or staged) and your changes https://www.drupal.org/documentation/git/interdiff

The coding standards fixes are: remove trailing whitespace, use 2 spaces instead of tabs, wrap comments to 80 characters. Details can be found here: https://www.drupal.org/coding-standards and dreditor.org can help visualize these.

sarvab’s picture

I see I didn't review this thread well enough before adding this patch update.

From what I gather, really the current patch to be reviewed is #82 and does not include any empty argument handling.

We should push to get that committed before dealing with empty arguments issue separately?

joelpittet’s picture

I missed #82 in my review, whoops. Teach me to scan recent patches.

Not sure the ramifications of not dealing with empty args. Will it be worse off?

sarvab’s picture

@joelpittet, from what I gather leaving it off can be semi-problematic but can be worked around in the views handler settings.

However including it can also be problematic for instance with multiple arguments you can't clear away empty ones except the last...

Maybe it's best to work that part out in the other issue?

joelpittet’s picture

Yes then if it can be worked out separately and has a work around, best to keep this the mvp for reviewers.

mustanggb’s picture

Status: Needs work » Reviewed & tested by the community

Back to RTBC'ing #82 then, as per #96.

geek-merlin’s picture

Thanks. (My fault i missed the issue number in my last comment =:-()

design.er’s picture

Is there a known time frame when this patch will be committed to the module and released as a new (dev or stable) version?

joelpittet’s picture

Status: Reviewed & tested by the community » Needs work
+++ b/plugins/selection/EntityReference_SelectionHandler_Views.class.php
@@ -9,12 +9,13 @@ class EntityReference_SelectionHandler_Views implements EntityReference_Selectio
-  protected function __construct($field, $instance) {
+  protected function __construct($field, $instance, $entity_type, $entity) {
     $this->field = $field;
     $this->instance = $instance;
+    $this->entity = $entity;

Noticed that we are now passing in the $entity_type but we are not storing it in a property, should we be?

Seems that if we are taking it in it should probably be stored on the object.

Also for all those properties they should have declarations, currently they are dynamic which isn't good practice.

Example:

  /**
   * The field object.
   *
   * @var object
   */
  protected $field;
geek-merlin’s picture

Good point.

+++ b/plugins/selection/EntityReference_SelectionHandler_Views.class.php
@@ -52,13 +53,32 @@ class EntityReference_SelectionHandler_Views implements EntityReference_Selectio
+        $info = entity_get_info($instance['entity_type']);

We have $entity_type already in the instance settings, so we can remove that from the constructor.
Declaring $entity property makes sense though.

karlshea’s picture

Status: Needs work » Needs review
StatusFileSize
new5.29 KB
new1.26 KB

Reroll on dev, interdiff from #82.

Now storing and declaring properties, and removed $entity_type from EntityReference_SelectionHandler_Views constructor.

robertgarrigos’s picture

As far I can see this is working for me now

robertgarrigos’s picture

Status: Needs review » Needs work

actually: I have this error when editing a node containing the reference field:

Fatal error: Cannot access protected property EntityReference_SelectionHandler_Views::$field in /.../sites/all/modules/entityconnect/entityconnect.module on line 210

karlshea’s picture

Status: Needs work » Needs review
StatusFileSize
new5.01 KB

The issue is that "good practice" is having protected declared properties, but that's not now other modules interact with entityreference because those properties haven't been protected in the past. EntityReference_SelectionHandler_Generic also doesn't have declared protected properties.

It seems that making a change like that is out of scope of this issue, since other modules will need to take into account those changes and getters/setters would need to be created.

I'm attaching a new patch without protected properties, which is basically a reroll of the patches before #172.

robertgarrigos’s picture

Great. This last patch is working for me now.

mustanggb’s picture

Status: Needs review » Reviewed & tested by the community

I've also tested #175 and it's working fine for me also.

Looks like all the feedback has been addressed so marking this as RTBC again.

EDIT: Actually, I ran into the array_filter() problem again, however as suggested by axel.rutz I've created #2815863: Contextual filter values of "" don't trigger "When the filter value is NOT available" for that.

Collins405’s picture

Yep, we tested this as well, and works great, looking forward to getting this committed soon. Thanks for your work on this!

  • spotzero committed 170134d on 7.x-1.x authored by KarlShea
    Issue #2010898 by axel.rutz, k.skarlatos, daro.pl, KarlShea, haggins,...
spotzero’s picture

Status: Reviewed & tested by the community » Fixed

Committed.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

geek-merlin’s picture

eaglegamma’s picture

Is this supposed to be working now? In Drupal 7.56, I've set up an entity reference view using a token that I believe should convert to a previously tested and working value, but with the token this shows no results. Please let me now if you'd like any more info!

w01f’s picture

Does Drupal 8 have this functionality? I can't seem to find any way to configure it for the entity reference field I want to pass a dynamic argument to from another field.

off’s picture

Still not working..

swilmes’s picture

I created a sandbox module to move this functionality (using contextual filters in entity reference fields) into its own filter. I think this may be the best route going forward. This has only been tested in my specific use case, but hopefully I can expand upon it to make it a viable solution going forward. Feel free to try it for now if you'd like. Contextual Filter Referer