For the Drupal 7 version of this issue, see #2010898: Use tokens for entity selection view arguments.
Entity Reference allows using a View of a specific display type to set the available options. This is good.
It's also possible to set arguments (contextual filters) on that view from the ER field config screen. This is also good.
Those arguments must be completely static. This is not good.
Rather, it should be possible to have dynamic, context-aware arguments. The most obvious is "the node that this is on", allowing the view to filter based on the node itself. Ideally, other "relational" contexts (Panels-style, or maybe just via token if that's easier) should be possible, such as "the author of the node this is on", "the OG of the node this is in" (my actual use case), etc.
That would greatly expand the potential flexibility of that view to do all sorts of context-aware select lists.
Of course, there's the obvious problem of what to do when creating a node (or user, or whatever other entity) the first time, since there is no "this" yet to refer to. I see two possible ways to address that:
1) Allow for a default value, or a different context to pull from if null. Eg, if there's no node owner, default to the current user. This would be configurable.
2) Punt that question to the View, where there is already fairly sane default argument capability. As long as we are able to do relational arguments, so that the contextual filter on the View doesn't have to be the entity type that it is on, that's probably sufficient and easier to implement anyway.
In my specific use case, I want to have an ER from a node to other nodes of type Foo that are in the same OG as the node being edited; if the node is being added, default to the user's OGs. The same concept would apply in many other situations, of course, such as related posts by the same author, etc.
(The current alternative involves writing a completely new custom views default argument plugin for every use case, which is highly sub-optimal.)
Thinking about it, I believe tokens would likely be the most straightforward way to specify such values.
So:
1) Is this feature something that would be accepted?
2) I MAY be able to get some time to work on this for the client project that requires it, if I knew it would be accepted so that we're not working with a project fork. :-) Is this doable? (If not, we'd have to fall back to the one-off above.)
Comment | File | Size | Author |
---|---|---|---|
#258 | interdiff-255-258.txt | 1.04 KB | mariacha1 |
#258 | 1699378-258.patch | 12.61 KB | mariacha1 |
#255 | 1699378-255.patch | 12.54 KB | ameymudras |
#254 | 1699378-254.patch | 12.36 KB | andreastkdf |
#253 | 1699378-allow-views-token-D9.5.9-1.patch | 12.39 KB | SocialNicheGuru |
Issue fork drupal-1699378
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #1
kholloway CreditAttribution: kholloway commentedI understand your frustration with this and came up with a work around:
I am using OG and needed to make an entity reference field on the Group Node to show all nodes that belong to that group.
There is a view that comes with OG that already does this. The problem is I couldn't pass the group ID (GID) of the current node to the view through the entity reference field.
The default "What to do when Filter NOT found" list wasn't helping at first. Group Context, NID from URL, weren't working.
Basically in the end I inspected the $field_state of the actual edit form itself (Devel or var_dump) and was able to access the auto-complete path inside the fields array:
$field_state->YOURFIELDNAME->...->['settings']['handler_settings']['view']['args'] (Think language ['und'] and [0] are part of the ... part as well).
All that to find that the auto-complete path (which is what the view sees) was:
/entityreference/autocomplete/single/YOURFIELDNAME/node/CONTENT_TYPE_NAME/NID
So, all you have to do to grab the NID (Or any of the other field information you get from that URL) is set your view to use the "Raw value from URL" option if filter is NOT present and set it for the correct offset. In this case NID is 7.
LONG STORY SHORT: (Read the last paragraph).
Comment #2
John Pitcairn CreditAttribution: John Pitcairn commentedThe ability to use tokens in the entityreference view arguments would be terrific, and I'd certainly use it that it were included in entityreference.
Comment #3
Crell CreditAttribution: Crell commenteddeviantpixel: Thanks, that sounds like a clever workaround. It only works for autocomplete-based widgets, though. If I have a select-based widget, there's no autocomplete to draw from.
Comment #4
guile2912 CreditAttribution: guile2912 commentedThis module is so great and I needed this , so here you go. Using tokens like [current-page:url:unaliased:args:value:1] makes this sooo powerfull :)
This patch if for the dev version, havent tryed it on rc3 yet . Please test it so we can have this included as soon as possible ! Thank you.
Comment #5
elliotttf CreditAttribution: elliotttf commentedThe patch in #4 works for me. The token to get a node id feels kind of hackish but I seem to recall that there's not a clean way to get at node tokens on node edit forms.
Comment #6
Crell CreditAttribution: Crell commentedThe aptch in #4 is lacking any token help. No one I know can write token strings from memory. :-) It needs the token help information attached. I'll work on that and report back.
Comment #7
Crell CreditAttribution: Crell commentedOK, my error. It does include the token selector thingie, but only if token module is enabled. :-) We should probably expose the token functionality only if token module is enabled. The attached patch does so.
Also, this only handles global tokens. Tokens based on the entity the form is on would be even better. However, we can probably save that for a follow-up patch.
Comment #8
Crell CreditAttribution: Crell commentedComment #9
robcarrWow! Thanks for working on this. The patch seems to work well, although I'm struggling to work out what the tokens would be for fields on the current form, so can't say how well it works on tokens relating to the current entity being edited. Tested with tokens relating to current user and site - fantastic.
Great feature, so hope it can be committed soon.
Comment #10
Crell CreditAttribution: Crell commentedarrrgh: What you're talking about are contextual tokens, eg, the $node being edited or the $user being edited. That's what I was referring to in #7. The trick there is that on entity add pages those will always be empty, so you need to have some sort of sane default handling or else build your view to have sane default handling. And even then, it would only apply to the node as it was saved previously; dynamically updating the form client-side is a totally different animal.
Comment #11
Damien Tournoud CreditAttribution: Damien Tournoud commentedOooo, nice patch!
^ The token module is actually only required to display the list of tokens in the UI, let's rewrite this so that it works.
^ This one is not used and should just go away.
^ We should use the proper context we have instead of a global token replacement. The entity type and entity being edited is passed by entity reference to
EntityReferenceHandler::getInstance()
. We can leverage it here.Comment #12
Crell CreditAttribution: Crell commentedSince the token module provides the UI, and the token system is basically unusable in a GUI without the token UI (really, does anyone remember token strings by heart? I don't), I think only enabling when token module is available is reasonable.
I left out the contextual instance above on simplicity grounds for now (and because my use case found an alternate approach, so I didn't have much further time to spare on this issue :-( ). Do you want that now, or in a follow-up patch?
Comment #13
guile2912 CreditAttribution: guile2912 commentedWell you should be able to disable the Token UI if you want , and still have the system working (otherwise, I would call this a bug).
So I the token module is available, show the help, otherwise, tell that you can have help if you activate it.
Comment #14
guile2912 CreditAttribution: guile2912 commentedSo here is a new patch.
It now manages the fact that the module "token" may not be available as Crell stated, and add a small sentence about it.
I took off what you said what not used.
I also had a deeper look into the context, but I have a bad news about it.
Because the entity reference fields does not know where it is the is nowhere we can get the nodeid being edited for example. So we cannot pass it to the token_replace function to have access to node tokens. I think that we may only be able to access global tokens on this one.
For info, help texts are split on purpose, because those strings may already be translated. If I glue them together, we would have to wait for them to be translated again.
Comment #15
guile2912 CreditAttribution: guile2912 commentedSo I guess it would be nice to have this little working piece of code to start with, and maybe later find a solid way to get the info we miss for now.
Comment #16
Damien Tournoud CreditAttribution: Damien Tournoud commentedAs I mentioned in #11:
Not having a proper entity in the token data makes this patch essentially useless.
Comment #17
guile2912 CreditAttribution: guile2912 commentedYou are really hard in business !!
I was so near of it before (but my test site uses filed collections, so that make things a little more complex) and here it works.
So here is a working patch with the entity in the token.
Comment #18
Damien Tournoud CreditAttribution: Damien Tournoud commentedThat's getting closer. Thanks for the hard work!
You are hardcoding the token type as the entity type here, which is a wrong assumption. For example, tokens for the
taxonomy_term
entity are calledterm
. The Entity API module provides us with a'token type'
key in the entity info. You need something like this:Comment #19
guile2912 CreditAttribution: guile2912 commentedThat was a good catch. You nearly wrote the whole code ^^
So here it is again, with the use of the entity_get_info everywhere where we need the token type.
Comment #20
MustangGB CreditAttribution: MustangGB commentedBasic functionality works on node edit pages, however not on node add pages. This is because, in my case, [node:field-testing:nid] is not tokenified. I think instead "When the filter value is NOT available" should be triggered, so I made the following changes:
Also it isn't able to pick-up field values that have been set with "entityreference_prepopulate".
How can we link this in with views ajax to get the select list autoupdated when, again in my example, the field-testing field is updated. This is an issue on both node add and edit pages.
Comments should probably be cleaned up as well, spaces after //, start with capital letter, finish with full stop, full sentences rather than fragments, no spaces after ( or before ).
Comment #21
Anonymous (not verified) CreditAttribution: Anonymous commentedThanks for this great patch! Using Drupal 7 with Postgresql, if the module 'Entity tokens' is installed , the process of triggering the field edition interface will run forever until displaying an error message related to memory allocation (http://drupal.org/node/1215630). after switching off the module 'Entity tokens', I got the patch seems to do his wonderful job: I can select the view argument among the tokens ([node:field_leadingorganization]) that will be passed to my entity reference view. But after that I get swamped in the reference view : how do I set the default value for the contextual filter . Do I use 'Raw value from URL' (how to guess the argument nr?) or PHP code?
Comment #22
MustangGB CreditAttribution: MustangGB commentedSo I've been trying to figure out the whole "dynamically updating the form client-side" however upon rebuilding the form the value in $this->entity does not change. Am I right in thinking this is because $this->entity only contains the saved data? If so how can I access the new form data in getReferencableEntities?
Comment #23
jadsam CreditAttribution: jadsam commentedHi,
Thanks for the post # 20
public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
...
+ $args = array_map('token_replace', $this->field['settings']['handler_settings']['view']['args'], array(array($this->entity_type_token => $this->entity)), array(array('clear' => TRUE)));
...
+ $result = $this->view->execute_display($display_name, (!array_filter($args) ? array() : $args));
...
}
I currently need this piece of code to add and/or modify nodes, however after applying the changes following the instruccions a got the error included in the Error.JPG file.
I will really appreciate any comment you can provide about this.
Thanks in advance.
Comment #24
willieseabrook CreditAttribution: willieseabrook commentedWow, what a great patch. #19 is working for me.
I have a URL like: /admin/commerce/orders/8888/message/add
Under Field Settings / Entity Selection / View arguments I have: [current-page:url:unaliased:args:value:3]
And it's working great - passing the 8888 into the view as an argument.
Comment #25
lsolesen CreditAttribution: lsolesen commentedThis comment has been moved into #1826676: Using the wrong id as key in the returned view when using views selection as it turned out it had nothing to do with this patch.
Comment #26
lsolesen CreditAttribution: lsolesen commentedDISREGARD THIS COMMENT.
Comment #27
lsolesen CreditAttribution: lsolesen commentedDISREGARD THIS COMMENT.
Comment #28
lsolesen CreditAttribution: lsolesen commentedRerolled. Cleaned up the comments and fixed some whitespace errors.
@akumustang: Could you try to implement your changes proposed in #20 in a changed patch?
Comment #29
lsolesen CreditAttribution: lsolesen commentedHm, missed some whitespace.
Comment #30
lsolesen CreditAttribution: lsolesen commentedMoved comments above lines.
Comment #31
lsolesen CreditAttribution: lsolesen commentedDON'T USE THIS PATCH.
Comment #33
lsolesen CreditAttribution: lsolesen commentedDON'T USE THIS PATCH.
Comment #34
MegaChriz CreditAttribution: MegaChriz commented@Isolesen #31
There shouldn't be a check for the token module when doing token_replace(), because that function is in Drupal core (since Drupal 7). See also #13 of this thread.
Comment #35
lsolesen CreditAttribution: lsolesen commented@MegaChriz One learns something everyday. Thanks. Then #30 is the proposed patch. Though I still haven't been able to solve #25 in the patch.
Comment #36
guile2912 CreditAttribution: guile2912 commentedIt seems that the patch #30 does not have the changes the #20 to have the functionnality of views "When the filter value is NOT available" working, Why ? Does it needs more testing ? ( I will give it a go soon )
Comment #37
lsolesen CreditAttribution: lsolesen commented@guile2912 Because I was not sure how that worked and was not sure how to test it.
Comment #38
MegaChriz CreditAttribution: MegaChriz commentedIn think the changes in #20 are left out in #30 because of the problems noted in #23.
Comment #39
lsolesen CreditAttribution: lsolesen commented@MegaChris Though I could not reproduce what was reported in #23 when trying to include that change in the patch.
Comment #40
guile2912 CreditAttribution: guile2912 commentedI am not sure either the #20 was the cause of the error #23 because #23 occurs because the view had problems beeing initialised ($view object does not exist ) and the #23 patch is just a rewrite of the argument string.
#21 is an error of entity_token, so we are good on our side.
I just tested #20 and it works great, providing the "When the filter value is NOT available" view behavior as expected.
So I guess we can put it in a patch and give it a go :)
Comment #41
lsolesen CreditAttribution: lsolesen commentedNow including comments in #23.
Comment #42
jadsam CreditAttribution: jadsam commented#41: view-argument-as-token-1699378-41.patch queued for re-testing.
Comment #43
MegaChriz CreditAttribution: MegaChriz commentedI have tested the patch #41. I've found two problems with it:
[node:nid]
as the View arguments.An error message is displayed when creating a new node when using
[node:nid]
as the View argumentsI added an Entity Reference field to a node type and I had set the View argument to
[node:nid]
. When editing an existing node, this lead to the desired results: the Node ID was passed to the View. But when adding a new node, that node doesn't have an ID yet and this resulted into the following error message:That leads me to think the following: maybe we should only pass the entity to token_replace() when the entity has an ID?
Only the first argument gets replaced with tokens from the entity
Look at the following piece of code (part of patch in #41):
This will result into that only for the first Views argument the entity will be passed to token_replace(). I have tested to pass two node tokens to Views and this resulted in the following error message:
So my suggestion is to just use a
foreach
instead ofarray_map()
.Patch
The attached patch addresses problem 1 and 2 (in addition of the patch in #41). Since token replacement happens in two places, I re-introduced the method
handleArgs()
(it was previously introduced by lsolesen in #31) where the token replacement takes place.The entity will only be passed to
token_replace()
when the entity has an ID. This is checked by callingentity_extract_ids()
.Comment #44
derekw CreditAttribution: derekw commentedDisregard
Comment #45
pmichelazzoGreat! #43 Working like a charm! Thank you!
Comment #46
jpstrikesback CreditAttribution: jpstrikesback commentedQuick change to fix a whitespace error, otherwise works.
Comment #47
jpstrikesback CreditAttribution: jpstrikesback commentedThis works wonderfully...I'm going to RTBC this myself as all I changed was whitespace.
Comment #48
sweethilit CreditAttribution: sweethilit commentedHi guys
I used the patch and it works fine for me.
The problem I am having now is that the field I am using for the token is another entity selection.
But when I change the selection of the field, the dynamic field does not change.
That is, I have a "location" field and a "Hotel" field.
I want the "hotel" field to populate according to the selection in the "location" field.
The "hotel" field draws its content from Entity selection view with a token argument (The token is the "location" field).
What I am looking for is to achieve an outcome in which the hotel field will change according to the selection in the location field.
Any help will be appreciated
Thanks,
sweethilit
Comment #49
Jelle_SPatch works like a charm. #48 looks like it should be in a separate feature/support request. It's out of scope for this patch.
RTBC++
Comment #50
Jelle_SFYI: Marked #1426984: Token support for Default Value as duplicate
Comment #51
Summit CreditAttribution: Summit commentedHi, http://drupal.org/node/1699378#comment-6809760 RTBC+++!!
Comment #52
maxplus CreditAttribution: maxplus commentedWow great, works for me, thanks!
Comment #53
jadsam CreditAttribution: jadsam commentedHi all,
I am a little bit confuse about how to implement this.
The user Crell at the begining of this threat said "The most obvious is "the node that this is on", allowing the view to filter based on the node itself".
If I try to update a content already created the view works fine because receives the contextual parameter (already saved in the database) before showing the content. As a result, the second control loads its content based on the saved value in the first control.
So, what I do not understand is the following, during the content creation, If I have two Entity Reference controls and the second is based on a view that receives a contextual parameter from the first Entity Reference, what would be the trigger for updating the view that loads the control. Currently, I assume that the second control waits for the parameter before showing the content, but it does not receive any value and if I change the value in first Entity Reference control does not make any change because the view is not updated.
I can understand how to make it work.
I would really appreciate any comment on this regard
Comment #54
GiorgosK#46 works as advertised RTBC
Comment #55
adellefrank CreditAttribution: adellefrank commented#46 works wonderfully for me, too. Thanks!
Comment #56
jpstrikesback CreditAttribution: jpstrikesback commentedComment #57
sraborg CreditAttribution: sraborg commentedWill these patches be implemented into the next official release? I'm not big on patches in general as I don't want to worry about overwriting them on the next update.
Comment #58
keyiyek CreditAttribution: keyiyek commentedWould it be possible to have in the Entity Reference view type an option "Argument Input" like the one for Panel Panes?
In this way Arguments would be fed by the context in a very cool way.
Comment #59
bnadem CreditAttribution: bnadem commented#46: view-argument-as-token-1699378-46.patch queued for re-testing.
Comment #60
bnadem CreditAttribution: bnadem commentedThanks a lot for sharing,
I wonder if there is a way to "fill" the entityreference field with the corresponding view result during "create/edit" mode ?!
Comment #61
Striky2 CreditAttribution: Striky2 commentedGreat topic. This is a long-time wished feature improvement. Will try the patch because it would certainly help to solve some of the limitations.
Just one question, why not even trying to jump directly in the full dynamic arguments model, passed in PHP.
Attached a screenshot of what would be the ideal... I tried to realize it but I'm stuck with how this is handled afterwards...
Comment #62
myselfhimself CreditAttribution: myselfhimself commentedHello I was able to test patch #46 successfully (using the following Views arguments token expression "[node:nid],[node:content-type]") !
Thank you very much for this great new feature !
Comment #63
dysrama CreditAttribution: dysrama commentedI was very happy to find this patch, but I don't understand why it's set up only to work for already existing entities?
// Check if the entity has an ID. If not, don't pass the entity to token_replace().
I made a new patch, and it works fine without this condition, and now it also works for adding new entities.
I've attached the slightly modified patch
Comment #64
MegaChriz CreditAttribution: MegaChriz commented@dysrama
Have you tested to use
[node:nid]
as a token argument? See also #43.Comment #65
dysrama CreditAttribution: dysrama commented@MegaChriz
Thanks for your reply, I hadn't seen the comment in #43 and no, I haven't tested with node:nid.
The reasoning behind not replacing tokens at all when the entity is new because of 1 token not working seems flawed to me though? In my usecase for example, it makes the patch useless.
Comment #66
Damien Tournoud CreditAttribution: Damien Tournoud commentedSorry guys, but at this point we are going to need this to go into core first.
Comment #67
jpstrikesback CreditAttribution: jpstrikesback commentedI agree with #65 as the notice seems to me a bug in core's token handling (if it is still an issue). Re: #66, I'll take a stab at 8.x shortly, should the component be views.module as selection plugins now live in their respective modules?
Comment #68
amateescu CreditAttribution: amateescu commentedI think it's fine to keep it in the ER component. The problem with a 8.x patch is that it cannot include any of the
module_exists('token')
parts, which will make it a lot less useful :(Comment #69
jpstrikesback CreditAttribution: jpstrikesback commentedIndeed but right now doesn't the token module handle form alters for adding the token popup/help for core text areas that support replacement? It handles the field description form alter I believe. In that case I think it's fine to (at least attempt to) go in without those items unless I'm missing something (likely)...
Comment #70
amateescu CreditAttribution: amateescu commentedIt's definitely ok to go with what we can in core and leave Token to do its job, I was just saying that it's unfortunate that core won't/can't provide an experience as nice as D7 contrib.
Comment #71
jpstrikesback CreditAttribution: jpstrikesback commented^^ Indeed...
First pass to see what breaks.
Comment #73
jpstrikesback CreditAttribution: jpstrikesback commented:)
oops guess handleArgs() should be publicComment #75
jpstrikesback CreditAttribution: jpstrikesback commentedHow to waste the testbot 101... I need coffee...
Comment #76
jpstrikesback CreditAttribution: jpstrikesback commentedComment #77
malberts CreditAttribution: malberts commentedAny updates on this?
I don't currently have the time to test the 8.x version, so I am in no position to hurry anyone along. But I would like to know the roadmap/timeline for getting this back to 7.x.
Is this a small(ish), less important issue that needs more eyes? Or is it more complicated on the 8.x side? Does #67 - #70 mean that the backported patch will need to be redone to more closely follow the 8.x patch? Or will it be safe to use the 7.x patch (#46) in the meantime? I realise there's no "upgrade path" between that and the eventual patch, but I assume it should not affect the data that has been entered already?
Comment #78
MustangGB CreditAttribution: MustangGB commentedDid anyone manage to figure out how to use the value of a previous form element to ajaxly update a views enabled entity reference list yet?
Comment #79
Kazanir CreditAttribution: Kazanir commentedakamustang: I was just coming here to post about that. The patch in #63 seems to otherwise work fine. I am not really sure where to start to figure this problem out though.
Comment #80
readyventure CreditAttribution: readyventure commentedThanks for the patch works like a charm !
Comment #81
Kazanir CreditAttribution: Kazanir commentedOkay, I implemented the AJAX discussion on a personal level using a combination of extending the EntityReference_SelectionHandler_Views class to have a setAjaxArgs method and telling its getReferenceableEntities method to prioritize that argument. I put the necessary AJAX code into a form alter and used the appropriate part of the $form_state['values'] to feed the selection handler class and regenerate the options list on every form call. It is clunky but functional.
I'm not sure if something like this is possible at the general level without a LOT of wizardry -- it would involve extending the selection handler class to accept a form_state variable and then doing logic on the fields present in the form_state to see if they somehow "match" the token that is set in the settings form -- it seems quite complex but I'm also not a mad wizard or anything so maybe someone has other (better) ideas.
Comment #82
joemoraca CreditAttribution: joemoraca commented@Kazanir .. any way you could share what you did - maybe someone can come up with a better way -- but I would love to just adapt to my needs.
I have two fields on a node add form. I want the second fields view argument to be updated when the user picks a value in the dropdown / checkbox of the first value
Thanks
Comment #83
Laz5530 CreditAttribution: Laz5530 commentedHi,
I have a group MY_GROUP and a content type TASK. TASK has a user-reference field: RESPONSIBLE.
When i make a new TASK i use an autocomplete field to chose the RESPONSIBLE user.
I dont want to assign TASK to anybody outside of MY_GROUP, so i just want to search for RESPONSIBE in user in MY_GROUP.
I set in TASK the field RESPONSIBLE: Entity selection on "Views: Filter by an entity reference view" and i chose the view GroupContributors (where i already defined a display type "Entity Reference".
But the view: GroupContributors needs a contexual filter, so i should give the ID of MY_GROUP from the URL to the field.) and type %1 for field:"arguments". But it does not work.
Have anybody some idea?
Thanx
Comment #84
guile2912 CreditAttribution: guile2912 commentedFor D7, #46 still works fine and apply cleanly
Comment #85
aoturoa CreditAttribution: aoturoa commented#46 works pretty good. Thanks.
Can I suggest to add 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, but others may disagree.
Here my suggestion on top of D7 patch from #46:
Comment #86
MegaChriz CreditAttribution: MegaChriz commentedAdded reference to the same issue for the Drupal 7 version of Entity reference module.
Comment #87
jadsam CreditAttribution: jadsam commentedIt seems the patch #75 does not work on with the last version of entity reference 7.x-1.1 (2013-Nov-20).
Please could you confirm if there was an update.
Thanks in advance
Comment #88
guile2912 CreditAttribution: guile2912 commented#75 is for D8, the last D7 patch in this thread is #46
Comment #89
MegaChriz CreditAttribution: MegaChriz commentedNo, see #2010898: Use tokens for entity selection view arguments for the Drupal 7 version of the patch. I've updated the issue summary to clarify this.
Comment #90
Musa.thomas#46 is ok for D7 but for my case I must to comment this line (216):
in
method.
For my case Ive got line item with reference and I want to send product_id before line_item is create (in add to cart commerce process)
Comment #91
kejmil CreditAttribution: kejmil commentedHello friends,
when I create a new content, I want the "title" (the mandatory fixed field) to have a specific form and to be generated automatically based on the filled fields.
That's why I've set a few nodes in "AUTO NODE LABEL" that generate my page title. It looks roughly like this: [node: field_per_degree_before_n] [node: field_per_first_name] [node: field_per_surname] [node: field_per_degree_after_n], [node: field_per_profession], [node: field_per_narozen]
Between some of that tokens I want to add comma "," but I want the comma to be generated only if token has value (e.c. the field of that token is filled). If not, then I do not want to generate this comma. The reason is that in the case of some no-filled fields I do not want to have commas generated, for example, the title incorrectly generated could look like this:
Ing. Kamil Blazek, , student,
correctly should look like this: Ing. Kamil Blazek, student
Why should be generated like this? Because I left empty field "field_per_degree_after_n" and "field_per_narozen" - so tokens are not added, but the commas yes, because they are as fixed text.
How can I ensure something like this: if "field_per_degree_after_n" haas value Than "," and if "field_per_narozen" has value Than ","?
I do not know PHP codes, so if there is some tool or if someone have solved already this php, could you help me and send me it? Also I have information to use function "implode". Also I do not know how. I am lost...
Please for help.
Thank you
Comment #92
kejmil CreditAttribution: kejmil commentedSolved:
[node:field_example]
Comment #93
geek-merlinwe should not use array_filter() here.
same here.
Does anyone remember what they were good for? PHP's == bitchyness will shoot our knee with that:
(same for 7.x patch)
Comment #94
geek-merlinHmmm, #75 does not apply anymore as quite some code ran away, so doing a manual re-roll.
Then i reverted the array_filter() introduced as a imho unholy hack in #20/23/85. I can now see the original idea to fix special use cases where an empty argumant at the end is taken away, but this will cause ugly things when the argument is not at the end, and in these cases an empty string should be passed which views should treat as unavailable argument (if not please file an issue about that).
(I am still a bit concerned about the argument separator "," as mentioned in #91. Using "/" like on the priview page has similar issues.
Best choice imho might be \n. But the separator is already in the code and this should go into a new isue.)
Comment #95
amateescu CreditAttribution: amateescu commentedSorry for not providing any feedback on this patch earlier :( Sadly, feature requests need to wait for 8.1.x now...
Comment #96
guile2912 CreditAttribution: guile2912 as a volunteer commentedSo does it mean we wait until we have a final 8.0 and then test this patch again ?
Comment #97
gappleHere's an updated version of the patch in #94. No code changes, just the file path has changed.
Comment #99
gappleThat last patch would do completely nothing at all.
Here's my attempt, which makes the EntityReferenceAutocompleteWidget store the information of the entity which has the reference field in its settings, which can then later be loaded by ViewsSelection.
Comment #101
gappleLast patch didn't handle validation properly, so here's a new one.
Comment #104
gappleUpdated patch for 8.2.x
Comment #106
howards CreditAttribution: howards commentedAnother attempt based on #94 ... hopefully tests will succeed...
Comment #107
gappleChanging to Needs Review for testbot...
Comment #109
geek-merlinThanks gapple for caring about this!
This does not make sense.
Why did you change the original #94 code? This should still work: (or not?)
(or did just your IDE's autocomplete trick you? ;-)
Comment #110
howards CreditAttribution: howards commented@axel.rutz quite plainly and simply: I'm an idiot. ;) I was looking through code and noticed between 8.0.x and 8.2.x some code had been removed, and I ... I don't know what the fsck I was thinking. ;)
Patching again with original code in new file. Let's hope tests pass... (It seemed to work in my dev environment.)
Comment #112
geek-merlinOK so it looks like $this->entity ran away too...
Comment #114
sylus CreditAttribution: sylus commentedI'm curious why $this->entity no longer works, don't suppose anyone can point to a change record? I'd love to get this tokens working again for 8.x-2.x :)
Comment #115
jonathanshawThe entity is made available in drupal/core/lib/Drupal/Core/Entity/EntityReferenceSelection/SelectionPluginManager.php
I wonder if these options get passed into this viewsSelectionHandler in its $plugin_definition argument. I don't really get how these plugins work, but it might be worth kinting $plugin_definition as a first shot.
Comment #116
jonathanshawFor what's its worth, $this->entity was removed in #2107243: Decouple entity reference selection plugins from field definitions
Comment #117
howards CreditAttribution: howards commentedIs this supposed to be postponed based on #2325899: UI fatal caused by views argument handlers no longer can provide their own default argument handling? In other words is the previous issue a "blocker?" I'm an idiot. Please learned me. :(
Comment #118
kurowski CreditAttribution: kurowski commentedI've adjusted the patch from #110 to work now that $this->entity is gone. This is my first Drupal patch so please feel free to tell me where to RTFM if I'm doing it wrong :)
Comment #120
kurowski CreditAttribution: kurowski commentedTrying again after fixing file paths and trailing whitespace.
Comment #121
kurowski CreditAttribution: kurowski commentedComment #124
Pilulu CreditAttribution: Pilulu at Axess Open Web Services commentedAfter trying without success theses patches, i purpose another way to do it
Comment #126
sanci91 CreditAttribution: sanci91 commentedIf I try the patch #120 it returns me the following error:
I'm trying it on drupal core 8.3.0
Comment #127
jonathanshawComment #128
pk188 CreditAttribution: pk188 at OpenSense Labs commentedRe rolled.
Comment #130
pk188 CreditAttribution: pk188 at OpenSense Labs commentedComment #131
jonathanshaw@pk188 Thanks for the reroll. Is #130 still a reroll? If not, please provide an interdiff.
@pilulu #124 and @sanci #126 can your provide steps to reproduce the problems you're having?
Comment #132
jonathanshaw@gapple's work in #99 - 104 was abandoned without discussion. Does anyone know why?
Comment #134
brtamas CreditAttribution: brtamas at Integral Vision Ltd commentedComment #135
brtamas CreditAttribution: brtamas at Integral Vision Ltd commentedComment #137
liquidcms CreditAttribution: liquidcms commentedAnyone know status of this for D7?
I see a patch in #46 (which i have been using) but this patch no longer applies and I don't see that it was ever committed. And then this thread got hijacked along the way somewhere for D8.
Comment #138
MegaChriz CreditAttribution: MegaChriz as a volunteer commented@liquidcms
A fix for the D7 version has already been committed. See #2010898: Use tokens for entity selection view arguments.
Comment #139
validollFixed the patch #135 due errors during field validation.
Comment #140
jonathanshaw@validoll please provide an interdiff.
This is all going to need tests. @validoll Can you say what the errors were, so we make sure we have test coverage for them.
Comment #141
validollIn previous path was added arguments handler
in
ViewsSelection::validateReferenceableEntities()
, but$this->configuration['entity']
is NULL, because handler created without entity arg inValidReferenceConstraintValidator::validate()
because of which we have empty args which has token as value.I hope it's enough.
Comment #142
ThomasHuong CreditAttribution: ThomasHuong commentedHi guy,
Just would like to provide you my patch for Drupal 8.4.x which is working very well, the entity is now passed to the View by registering this token [node:nid]. Hope this helps.
Comment #143
jonathanshaw@ThomasHuong please provide an interdiff so we can see your improvements
Comment #144
colanYes, when posting patches, please also provide interdiffs, or we can't evaluate them relative to previous patches. See Creating an interdiff for details.
Comment #145
howards CreditAttribution: howards commentedSimple re-roll of #139 for 8.5.x, no additional changes.
Comment #147
zerolab CreditAttribution: zerolab at Torchbox for The Chartered Society of Physiotherapy commentedThis needs tests.
Also will fail for
ViewsExposedForm
(e.g. on /admin/content). Needs to check that$form_object
has thegetEntity
method.Will try to provide a patch later.
Comment #148
andreyks CreditAttribution: andreyks at Adyax commentedPatch 145 breaks form what doesn't extend EntityForm. Small fix for it.
Comment #149
andreyks CreditAttribution: andreyks at Adyax commentedComment #151
howards CreditAttribution: howards commentedNR for tests on #148
Comment #155
jonathanshawA second occurrence was missed.
Also, isn't Zerolab's suggestion to check that the method exists better than checking this is an EntityForm? Could someone have a custom form class with a getEntity method?
Comment #156
manuel.adan#145 nor #148 work for me. As far I can see, the handleArgs method is never called. In #142 it does, so it was lost at some point. The missing diffs are in getReferenceableEntities and validateReferenceableEntities:
I fixed it.
Also I did the following:
This patch is still for 8.5.x, should be ported to 8.6.x.
Comment #157
manuel.adanComment #158
jonathanshawGreat work @manuel.adan!
@Zerolab said that our check ( he seemed to mean
$form_object instanceof EntityForm
)But ViewsExposedForm doesn't have a getEntity method, so I'm confused.
I would think we should at least be checking using the interface though:
if (isset($form_object) && $form_object instanceof EntityFormInterface) {
Comment #159
zerolab CreditAttribution: zerolab at Torchbox for The Chartered Society of Physiotherapy commented@jonathanshaw the #145 patch did not have any checks whatsoever.The
$form_object instanceof EntityForm
check should do the trick.A few notes:
As @jonathanshaw mentioned, the check should be on the
EntityFormInterface
. Also, no need to checkisset($form_object)
becauseinstanceof EntityFormInterface
will return false if$form_object
is not set.We already check that this is an entity form instance. As such, there will always be an entity, there is no need for the
isset($entity)
checkComment #161
ZaunerD CreditAttribution: ZaunerD commented#156 works fine for me, however I noticed one bug:
Suppose you use a token that renders to multiple values and exposes a "join" modifier, you cannot use a comma as "join" parameter.
Example:
[user:roles:join:,]
This ends up in the argument being split at the ",":
Args:
- [user:roles:join:
- ]
Comment #162
jonathanshawre #161 we're just doing using the token service's replace method, I'm not sure it's the fault of this patch.
Comment #163
1kenthomas CreditAttribution: 1kenthomas as a volunteer and commented@joemoraca #82: (or anyone else) I just implemented this via AJAX callback and could share example code that is specific to two fields, if helpful to anyone.
Comment #164
kirkdeam CreditAttribution: kirkdeam commentedThe patches for this issue, and the solution they give, creates a huge database leak.
In my case, the table key_value size is sky high, and never-ending because of the $selection_settings_key being unique every time I change a field's value on any entity that has the autocomplete field, and never deleting the old record. I'm not sure if this happens because of misuse by my side, or because of the way the patches for this issue handles things. Maybe it's better to save the entity id and type instead of saving the whole entity object.
Comment #165
jonathanshawRe#164 Stashing the whole entity in a setting was introduced in #134 I think; prior versions used the entity type and id.
There are actually multiple different lineages of this patch within this issue, we keep rerolling and improving different versions without discussing which approach is basically right or even getting clarity on what the different approaches are.
Not all versions store anything in a setting.
If anyone wants to work on this issue, I suggest they go back to the beginning and try to understand what the different approaches/choices there are in this issue and write a summary of them.
Comment #166
geek-merlin> If anyone wants to work on this issue, I suggest they go back to the beginning and try to understand what the different approaches/choices there are in this issue and write a summary of them.
❤!
Comment #167
PQ CreditAttribution: PQ commentedI've had the patch from #156 in use for some months now but encountered a significant issue today.
If an entity has an entity reference field that uses views selection and has an entity token passed to the arguments e.g.
[node:nid]
, then attempts to update the parent entity via a JSONAPI patch request will cause a leaked metadata error as the entity is validated during early rendering and as part of that, it ends up replacing the token to validate the entity reference field. This causes cache metadata (e.g. the cachetag for "node:x") to be generated during early rendering.note, I haven't tried this with REST patch attempts yet so I don't know if the issue exists there too.
I'm not a 100% certain if this should be considered a bug in this patch, in the JSONAPI module or in core in general.
Comment #168
PQ CreditAttribution: PQ commentedAfter discussing it with @gabesullice on Slack, I've raised #3004546: Token generation during $entity>validate() causes leaked metadata in PATCH requests for the above bug in the jsonapi queue.
Comment #169
PQ CreditAttribution: PQ commentedAfter further discussion with @Wim Leers in #3004546: Token generation during $entity>validate() causes leaked metadata in PATCH requests, it looks like the above point should be dealt with here.
I've added an update to the patch that allows a
BubbleableMetadata
to be passed intoViewsSelection::token->replace()
in order to prevent cacheable metadata from bubbling to the render context, and made this happen whenViewsSelection::handleArgs()
is called fromViewsSelection::validateReferenceableEntities()
but notViewsSelection::getReferenceableEntities()
which means that the metadata generated from the token replacement should be used when generating the form element but not when validating it's value.Comment #170
PQ CreditAttribution: PQ commentedChanged issue status
Comment #171
Wim LeersHuh, this is weird, I don't see this in core?It's being added by this issue, of course.In forms, we don't tend to associate cacheability metadata simply because 99% forms will never be cacheable.
Similarly, when saving or validating entities, we don't tend to do this either, since those are changing the state of Drupal data and hence the response to that request is not cacheable anyway. So this looks fine to me.
Note that if this
ViewsSelection
class ends up being used by aViewsArgument
plugin like the IS seems to suggest, then it would become necessary to bubble.Comment #172
PanchoWhile the token browser integration was purposely removed between #63 and #71 (that's Token module's job), the legitimate notice "This field supports tokens." got lost somewhere between #130 and #134. Enclosed patch brings it back.
Other than that, everything seems to work fine, so far.
For convenience I'm also including a followup patch against Token module that brings back proper token browser integration.
Comment #173
PanchoAs pointed out above in #20 as well as (for D7 entity_reference) in #2830703: Empty token entity selection view arguments break:
An empty token replacement value will be passed to Views as an empty string (""), so the case that "the filter value is NOT available" isn't triggered.
We need to set a NULL value if the token service returns an empty string, to make sure Views considers it an empty argument.
Comment #174
PanchoSorry, last minute variable renames always result in a botched patch. Here's the correct one.
Comment #176
PanchoInstead of #174, we can sanitize the empty string in ViewExecutable which should be the slightly better approach (and the one axel.rutz proposed in #94, if I get him right).
Working patch in #3027640-5: Empty strings ("") passed in as contextual filter argument aren't considered missing. If we prefer this route, we'd stick with #172 here.
Comment #177
jonathanshawComment #178
opiPatch from #174 should probably be rerolled against https://www.drupal.org/node/2174633 (Can't applied #174 patch if 2174633#238 is also applied).
Comment #180
hkirsman CreditAttribution: hkirsman commentedFor me latest patch seems to filter the nodes but when saving I get error:
otice: Undefined index: #parents in Drupal\Core\Form\FormState->getError() (line 1112 of /app/web/core/lib/Drupal/Core/Form/FormState.php) #0 /app/web/core/includes/bootstrap.inc(584): _drupal_error_handler_real(8, 'Undefined index...', '/app/web/core/l...', 1112, Array) #1 /app/web/core/lib/Drupal/Core/Form/FormState.php(1112): _drupal_error_handler(8, 'Undefined index...', '/app/web/core/l...', 1112, Array) #2 /app/web/core/lib/Drupal/Core/Form/FormErrorHandler.php(164): Drupal\Core\Form\FormState->getError(Array) #3 /app/web/core/lib/Drupal/Core/Form/FormErrorHandler.php(124): Drupal\Core\Form\FormErrorHandler->setElementErrorsFromFormState(Array, Object(Drupal\Core\Form\FormState), Array) #4 /app/web/core/lib/Drupal/Core/Form/FormErrorHandler.php(124): Drupal\Core\Form\FormErrorHandler->setElementErrorsFromFormState(Array, Object(Drupal\Core\Form\FormState), Array) #5 /app/web/core/lib/Drupal/Core/Form/FormErrorHandler.php(124): Drupal\Core\Form\FormErrorHandler->setElementErrorsFromFormState(Array, Object(Drupal\Core\Form\FormState), Array) #6 /app/web/core/lib/Drupal/Core/Form/FormErrorHandler.php(124): Drupal\Core\Form\FormErrorHandler->setElementErrorsFromFormState(Array, Object(Drupal\Core\Form\FormState), Array) #7 /app/web/core/lib/Drupal/Core/Form/FormErrorHandler.php(124): Drupal\Core\Form\FormErrorHandler->setElementErrorsFromFormState(Array, Object(Drupal\Core\Form\FormState), Array) #8 /app/web/core/lib/Drupal/Core/Form/FormErrorHandler.php(26): Drupal\Core\Form\FormErrorHandler->setElementErrorsFromFormState(Array, Object(Drupal\Core\Form\FormState)) #9 /app/web/core/lib/Drupal/Core/Form/FormValidator.php(201): Drupal\Core\Form\FormErrorHandler->handleFormErrors(Array, Object(Drupal\Core\Form\FormState)) #10 /app/web/core/lib/Drupal/Core/Form/FormValidator.php(119): Drupal\Core\Form\FormValidator->finalizeValidation(Array, Object(Drupal\Core\Form\FormState), 'node_advanced_p...') #11 /app/web/core/lib/Drupal/Core/Form/FormBuilder.php(575): Drupal\Core\Form\FormValidator->validateForm('node_advanced_p...', Array, Object(Drupal\Core\Form\FormState)) #12 /app/web/core/lib/Drupal/Core/Form/FormBuilder.php(318): Drupal\Core\Form\FormBuilder->processForm('node_advanced_p...', Array, Object(Drupal\Core\Form\FormState)) #13 /app/web/core/lib/Drupal/Core/Controller/FormController.php(93): Drupal\Core\Form\FormBuilder->buildForm('node_advanced_p...', Object(Drupal\Core\Form\FormState)) #14 [internal function]: Drupal\Core\Controller\FormController->getContentResult(Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\RouteMatch)) #15 /app/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(123): call_user_func_array(Array, Array) #16 /app/web/core/lib/Drupal/Core/Render/Renderer.php(582): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() #17 /app/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(124): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure)) #18 /app/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(97): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) #19 /app/vendor/symfony/http-kernel/HttpKernel.php(151): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() #20 /app/vendor/symfony/http-kernel/HttpKernel.php(68): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1) #21 /app/web/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #22 /app/web/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #23 /app/web/core/modules/page_cache/src/StackMiddleware/PageCache.php(99): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #24 /app/web/core/modules/page_cache/src/StackMiddleware/PageCache.php(78): Drupal\page_cache\StackMiddleware\PageCache-
Comment #181
elpino CreditAttribution: elpino as a volunteer commented@1kenthomas #163 #1699378-163: Allow tokens in entity reference views selection arguments
I'm interested in your AJAX solution, could you share it? maybe it can even be incorporated
Comment #182
isalmanhaider CreditAttribution: isalmanhaider as a volunteer commentedApplied #174 which lead to the following errors, screenshot: http://prntscr.com/ngmzgm
Please note: I am using business rules instead of default entity reference views
Comment #183
steveoriolThe patch #174 does not apply on the version 8.7.1 of drupal ...
Comment #184
andeersg CreditAttribution: andeersg at Bouvet commentedI also had a problem with #174 on 8.7.1 so I tried to fix it.
The problem is that "core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php" has been altered. I tried to just add the same things as in #174, but in 8.7.1 this part is removed:
So I did not add this change:
Comment #185
steveoriolThanks andeersg, it works :-)
Comment #186
marco-sPatch #184 works! The ability to use tokens is a great feature! Thanks!
Comment #187
yogeshmpawarComment #188
yogeshmpawarRemoved unused use statement & resolved coding standard issue.
Comment #189
colanAs per #178, the work here is definitely conflicting with #2174633: View output is not used for entityreference options. Let's get that one in first because it has tests, too many comments, it's blocking other things, and it's hopefully ready.
Here's a quick patch that needs work, but should be able to be applied on top of that one. (Yes, you need to apply that one first.) I can't post an interdiff because it's failing due to the different baselines.
Comment #190
colanFor those interested in extending this functionality with AJAX, see #3073970: Add AJAX support to fields using Dynamic Views Arguments via Tokens.
Comment #191
kevin.dutra CreditAttribution: kevin.dutra at Workday, Inc. commentedFYI, the current solution causes
key_value
to accrue large amounts of data over time that will never be removed. More info over on #3076407: Use expirable key/value for entity autocomplete, although a solution to this problem is not currently available there. :(Comment #193
colan#189 needs review, but we're at NW because of #191 so setting that status now that #2174633: View output is not used for entityreference options is out of the way.
Edit: Needs a re-roll anyway as the patch doesn't apply to 8.9.x now.
Comment #194
frega CreditAttribution: frega as a volunteer commentedRerolled patch so it applies again to 8.9.x (and 8.8.x). Given that #2174633 has been fixed i am setting this to `needs review` again.
Comment #195
frega CreditAttribution: frega as a volunteer commentedSorry, i b0rked the patch first time round. Rerolled again, so it applies :/
Comment #196
frega CreditAttribution: frega as a volunteer commentedSorry, missed a small
use
statement in the reroll >.<.Comment #197
colanBack to NW. See #191.
Comment #198
Qandeel CreditAttribution: Qandeel as a volunteer commentedThere is an instance where some time the views execution display throws error on NULL return value; this happens when using conditional fields and one of the field involved in dynamic views argument via token setup is used in conditional fields and when that row is edited it throws following error.
The website encountered an unexpected error. Please try again later.
TypeError: Return value of Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection::getDisplayExecutionResults() must be of the type array, null returned in Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection->getDisplayExecutionResults() (line 290 of core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php).
to fix this I need to return NULL value as array.
To accomodate this I have added this in to the patch.
Comment #199
Qandeel CreditAttribution: Qandeel as a volunteer commentedComment #200
Qandeel CreditAttribution: Qandeel as a volunteer commentedHere is a patch that will work with latest Drupal version
Comment #201
el1_1el CreditAttribution: el1_1el commented200 working for me on v8.8.1. Thanks!
Comment #202
colan#198: Please provide interdiffs when posting patches. Thanks.
Comment #203
colanComment #204
jungleRe #202 attaching an interdiff for #200
Comment #206
graker CreditAttribution: graker commented#200 is working for me in a sense that I can add tokens to entity reference view field configuration. But I can't make much use of it because for my case I need an url part of the page on which the autocomplete is running. But when I look in the form, ['#selection_settings']['view']['arguments'] of my field still contains unprocessed (not replaced) token. And it only gets to be processed later when the url is /entityreference/user/somecache. So the replaced value is build based on the autocomplete route that doesn't contain the data I need.
But from comments in the start of this issue (#4, #24) I gathered that there was a way to process token from original page and pass it to the view (although it seems that it was for Drupal 7). Isn't it the case any more for Drupal 8? Is there a way to pass an argument to the view that is based on a route of the page that has the form field on it rather than an autocomplete route?
Thanks!
Comment #207
rfsbsbI can confirm #200 works on Drupal 8.8.1.
Comment #208
anushrikumari CreditAttribution: anushrikumari at OpenSense Labs commentedRerolled patch for 9.1.x
Comment #210
nikitagupta CreditAttribution: nikitagupta at Srijan | A Material+ Company for Drupal India Association commentedComment #212
mparker17Here is the patch from #210 rebased onto 8.9.x and 9.0.x (no interdiff because no changes).
Comment #213
geek-merlinLet's move this forward.
In #193 this is set to NW as of #191 which states
That issue states
So when this patch stores current entity in $settings, it worsens an already existing problem.
So we can (rough ideas)
a) Check if we can unset the entity after use OR
b) Find another place to pass around or retrieve current entity OR
d) Reduce the data passed around by e.g. replacing tokens earlier
d) do nothing and rely on the other issue solving that problem
In any case, this needs tests.
Comment #214
geek-merlinLet's move this forward.
In #193 this is set to NW as of #191 which states
That issue states
So when this patch stores current entity in $settings, it worsens an already existing problem.
So we can
a) Check if we can unset the entity after use OR
b) Find another place to pass around or retrieve current entity OR
c) do nothing and rely on the other issue solving that problem
In any case, this needs tests.
Comment #216
Nigel CunninghamHi all.
I've tested the patch and found that it doesn't work when the autocomplete you're seeking to use is in a subform. The attached patch addresses this, looking for a closer entity in the form structure. My test case is editing a commerce order item within a commerce order (/admin/commerce/orders/).
In addition to that, I've modified the patch so it doesn't store the whole entity in the settings, but rather just the entity type and id.
The issues mentioned in the previous comment still apply.
Comment #217
Nigel CunninghamI've started using views_entity_form_field today, and found in there a use case for extending the patch to handle views as well.
Here's an update.
Comment #218
Nigel Cunningham(Correct my malformed patch in the last comment)
Comment #219
jonathanshaw@NigelCunningham please post an interdiff, it really helps to understand your changes.
Comment #220
Nigel CunninghamHere's an updated version with a fix for a bug in the views support that I discovered this morning.
@jonathanshaw, sure. Attaching vs 210.
Comment #221
Nigel CunninghamAh, I'm having a marvelous start to the day. Accidentally included core/Patches.txt in the last upload, which prevents composer from being able to install it. Right this time. (Patch prepared for 8.9 by the way).
Comment #222
Nigel CunninghamPreparing a 9.2.x version too. No changes.
Comment #223
barrio CreditAttribution: barrio commentedEDITED: Don't use my patch, use Nigel's 222 one, which is more than right. Mine adds no value, sorry for the confusion.
Comment #224
akalam CreditAttribution: akalam commentedComment #225
Gauravvvv CreditAttribution: Gauravvvv at OpenSense Labs commentedRe-rolled patch #222, Fixed cs issues. Please review.
Comment #226
Gauravvvv CreditAttribution: Gauravvvv at OpenSense Labs commentedComment #228
SerShevchykThe patch #225 works fine for me on D 9.2.7
Comment #231
Nigel CunninghamUpdated the patch from #225 to apply against 9.4.x and put into a MR. The only rejects were changes already applied in the 9.4.x branch; the patch is otherwise unchanged.
Comment #232
kopeboy CreditAttribution: kopeboy commentedSorry for the intrusion, but what's the syntax to be used in the field setting for passing the View argument? Token style or Twig style? How to check available variables?
Comment #233
aludescher CreditAttribution: aludescher at drunomics for Porsche Informatik Gesellschaft m.b.H. commentedUpdated the patch from #225 to apply against 9.3.x
Comment #234
anruetherFYI There is also views_tokenized module by @mxh. Not sure though, how much it overlaps.
Comment #235
ankithashettyFixed custom command failure in #233, thanks!
Comment #237
Nigel Cunningham@kopeboy there is no syntax - the code figures out what entities apply from the context.
Comment #239
cgrader CreditAttribution: cgrader at Porsche Informatik Gesellschaft m.b.H. commentedRemoved one code beautifying line from last patch, because it was incompatible the patch from issue https://www.drupal.org/project/drupal/issues/2776571.
The patch is based on Drupal core 9.3.15. Please note that I did not fix the unit test.
Comment #241
maurizio.ganovelliAttached a new patch based on Drupal core 9.5.x.
Comment #242
maurizio.ganovelliUndoing version change.
Comment #243
ameymudras CreditAttribution: ameymudras at Salsa Digital commentedComment #244
ameymudras CreditAttribution: ameymudras at Salsa Digital commentedTrying to fix the CCF
Comment #245
Jon PughThis breaks when trying to create new nodes with a reference field.
It's because there's no ID yet to pass.
I got it working by altering handleArgs:
- if (isset($this->configuration['entity_info'])) {
+ if (isset($this->configuration['entity_info']) && $this->configuration['entity_info']['id']) {
Comment #247
mariacha1 CreditAttribution: mariacha1 at ThinkShout commentedThis removal of the "use" statement is throwing an error for me, and it doesn't seem relevant to the rest of the code changes in this file. Maybe this was an accident?
Adding it back to 245 fixes it for me.
Comment #248
very_random_man CreditAttribution: very_random_man as a volunteer commentedI recently came across this whilst recreating a D7 site (yay, token arguments) in D9 (booo, no token arguments). In case anyone is looking for a workaround for dynamic arguments to entity reference view displays whilst this issue gets resolved, you can specify the arguments in a form_alter like this:
Comment #249
mariacha1 CreditAttribution: mariacha1 at ThinkShout commentedHere's a reroll of the patch for 9.5.9.
Comment #250
SocialNicheGuru CreditAttribution: SocialNicheGuru commentedThis patch is causing this issue in the ECA module, #3358158: Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection::__construct(): Argument #8 ($token) must be of type Drupal\views\Plugin\EntityReferenceSelection\Token, Drupal\eca\Token\ContribToken given
I suspect adding the token parameter will also break other modules that define token classes.
Comment #252
SocialNicheGuru CreditAttribution: SocialNicheGuru commentedRerolled JonPugh #245 for Drupal 9.5.9
Comment #253
SocialNicheGuru CreditAttribution: SocialNicheGuru commentedin #245 and #252 this line is removed:
-use Drupal\Core\StringTranslation\StringTranslationTrait;
I had to add this line back in. I had fatal error:
"PHP message: PHP Fatal error: Trait "Drupal\views\Plugin\EntityReferenceSelection\StringTranslationTrait" not found in /drupal9.5.9/html/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php on line 32
Comment #254
andreastkdf CreditAttribution: andreastkdf at Soapbox Communications Ltd commentedre-roll for 10.1.x
Comment #255
ameymudras CreditAttribution: ameymudras at Salsa Digital commentedCouldn't generate the interdiff, changes to fix the issue with above patch and compatibility
Comment #256
smustgrave CreditAttribution: smustgrave at Mobomo commentedSeems to have test failures.
Also was previously tagged for tests and issue summary which appear to still be needed.
Comment #257
chucksimply CreditAttribution: chucksimply commentedfor 10.1.6, #247 failed. #254 applied and works as needed.
Comment #258
mariacha1 CreditAttribution: mariacha1 at ThinkShout commentedHere's a quick reroll. I D10 I was seeing errors about there being no value for "$element['#array_parents']" on regular node forms for any select or radio fields added directly to the top-level of the form. This updated patch just wraps the foreach that loops through array_parents in an if statement.