Version "8.x-2.x-dev" is not working for me to prepopulate entity reference fields.

Here's the fix that worked for me:

In the prepopulate\src\Controller\prepopulateController.php file, replace line 47. Line 47 is

        $form['widget'][0]['value']['#value'] = $request_slice;

Replace line 47 with the following six lines:

        if (isset($form['widget'][0]['value'])) {
          $form['widget'][0]['value']['#value'] = $request_slice;
        }
        else if (isset($form['widget'][0]['target_id'])) {
          $form['widget'][0]['target_id']['#value'] = $request_slice;
        }

And, below is an example of a relative URI that I was able to get working with this code change. This example is for:

  • creating a new node of content type "page"
  • prepopulating that new node's entity reference field that has the machine name "field_page"
  • prepopulating that field so that it points to the node with the title "ExistingNodeTitle" and the id "45"
/node/add/page?edit[field_page]=ExistingNodeTitle%20(45)

Comments

JonAtDrupalOrg created an issue. See original summary.

juliencarnot’s picture

Thanks a lot for sharing your fix, I happen to have the same problem: I want to create a node of the "project" type, referenced to a "resource" type node. So I created a field name "field_p_resource", which I can use with autocomplete on the project add node form (just filling the title of the resource). This field can have unlimited values. In the form, its name attribute is "field_p_resource[0][target_id]" and its label is "Ressource utilisée".

I've read the doc, specifically the part on entity reference, which gives this example:
node/add/content?edit[field_example_entity][und][DELTA][target_id]=Entity%20label%20(ENTITY_ID)

but I'm not exactly sure what my own parameters should be, so I tried this and a lot of other combinations, with no luck:
node/add/project?edit[field_p_resource][0][target_id]=Ressource%20utilisée(49)
(49 being the id of my resource node)

I get this error message, with or without the replacement you suggested:

Notice: Undefined index: #type in Drupal\prepopulate\Controller\prepopulateController->_prepopulate_request_walk() (line 32 of modules/prepopulate/src/Controller/prepopulateController.php).

Drupal\prepopulate\Controller\prepopulateController->_prepopulate_request_walk(Array, Array)
prepopulate_after_build(Array, Object)
call_user_func_array('prepopulate_after_build', Array)
Drupal\Core\Form\FormBuilder->doBuildForm('node_project_form', Array, Object)
Drupal\Core\Form\FormBuilder->processForm('node_project_form', Array, Object)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object)
Drupal\Core\Entity\EntityFormBuilder->getForm(Object)
Drupal\node\Controller\NodeController->add(Object)
call_user_func_array(Array, Array)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
call_user_func_array(Object, Array)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1)
Stack\StackedHttpKernel->handle(Object, 1, 1)
Drupal\Core\DrupalKernel->handle(Object)

Any hints would be very much appreciated!

JonFreed’s picture

Issue summary: View changes

@juliencarnot, Try removing the "[0][target_id]" from your URI and putting a space ("%20") after "utilisée" and before "(49)".

I'm also updating the issue text to include an example of a relative URI that I was able to use successfully with the code change.

juliencarnot’s picture

Thank you so much @JonFreed for the answer and example/explaination, it was one of the combinations I hadn't tried and it worked!

I get an additional notice message on the node add page and on the node page after it is submitted, still related to the type undefined index. I'll copy it here it is so others can find this issue:

    Notice: Undefined index: #type in Drupal\prepopulate\Controller\prepopulateController->_prepopulate_request_walk() (line 32 of modules/prepopulate/src/Controller/prepopulateController.php).

    Drupal\prepopulate\Controller\prepopulateController->_prepopulate_request_walk(Array, Array)
    prepopulate_after_build(Array, Object)
    call_user_func_array('prepopulate_after_build', Array)
    Drupal\Core\Form\FormBuilder->doBuildForm('node_project_form', Array, Object)
    Drupal\Core\Form\FormBuilder->processForm('node_project_form', Array, Object)
    Drupal\Core\Form\FormBuilder->buildForm(Object, Object)
    Drupal\Core\Entity\EntityFormBuilder->getForm(Object)
    Drupal\node\Controller\NodeController->add(Object)
    call_user_func_array(Array, Array)
    Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
    Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object)
    Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array)
    Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
    call_user_func_array(Object, Array)
    Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1)
    Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
    Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
    Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1)
    Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1)
    Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1)
    Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1)
    Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1)
    Stack\StackedHttpKernel->handle(Object, 1, 1)
    Drupal\Core\DrupalKernel->handle(Object)

    Notice: Undefined index: value in Drupal\prepopulate\Controller\prepopulateController->_prepopulate_request_walk() (line 43 of modules/prepopulate/src/Controller/prepopulateController.php).

    Drupal\prepopulate\Controller\prepopulateController->_prepopulate_request_walk(Array, 'Usine désaffectée (49)')
    Drupal\prepopulate\Controller\prepopulateController->_prepopulate_request_walk(Array, Array)
    prepopulate_after_build(Array, Object)
    call_user_func_array('prepopulate_after_build', Array)
    Drupal\Core\Form\FormBuilder->doBuildForm('node_project_form', Array, Object)
    Drupal\Core\Form\FormBuilder->processForm('node_project_form', Array, Object)
    Drupal\Core\Form\FormBuilder->buildForm(Object, Object)
    Drupal\Core\Entity\EntityFormBuilder->getForm(Object)
    Drupal\node\Controller\NodeController->add(Object)
    call_user_func_array(Array, Array)
    Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
    Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object)
    Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array)
    Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
    call_user_func_array(Object, Array)
    Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1)
    Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
    Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
    Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1)
    Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1)
    Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1)
    Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1)
    Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1)
    Stack\StackedHttpKernel->handle(Object, 1, 1)
    Drupal\Core\DrupalKernel->handle(Object)
jehon’s picture

Hello

The fix worked for me too. Great.

Would it be possible to go one step further? Having the url containing "/node/add/page?edit[field_page]=45" (the node id) only seems more robust to me...

Thanks in advance,
Jean

jehon’s picture

So I propose this code:

        if (isset($form['widget'][0]['value'])) {
          $form['widget'][0]['value']['#value'] = $request_slice;
        } else if (isset($form['widget'][0]['target_id'])) {
          if (is_numeric($request_slice) && ($target_node = \Drupal\node\Entity\Node::load($request_slice))) {
            $form['widget'][0]['target_id']['#value'] = $target_node->getTitle() . ' (' . $request_slice . ')';
          } else {
            $form['widget'][0]['target_id']['#value'] = $request_slice;
          }
        }

The code use this to fill in the complete title, if the requested parameter is an integer:

Check that the element exists and get it:

($target_node = \Drupal\node\Entity\Node::load($request_slice))

Get the title:

$target_node->getTitle()

But since I don't understand very well Drupal api, you should check twice if it would not break anything anywhere else...

The first thing in my mind is that could open a security hole: this allow anybody to get the title of any node...

jehon’s picture

So here is a version wich protect against discovering titles:

        if (isset($form['widget'][0]['value'])) {
          $form['widget'][0]['value']['#value'] = $request_slice;
        } else if (isset($form['widget'][0]['target_id'])) {
          // Referenced element: look for name ? Title (id)
          if (is_numeric($request_slice) && ($target_node = \Drupal\node\Entity\Node::load($request_slice)) && $target_node->access()) {
            die("immediately");
            $form['widget'][0]['target_id']['#value'] = $target_node->getTitle() . ' (' . $request_slice . ')';
          } else {
            $form['widget'][0]['target_id']['#value'] = $request_slice;
          }
        }

The test use this to check if the user has an access to the node:

 && $target_node->access()
juliencarnot’s picture

Status: Active » Needs review
StatusFileSize
new839 bytes

Just put the initially suggested fix in a patch, to be reviewed.

@jehon: sorry I'm not qualified to evaluate your suggestion, sounds like an interesting feature though!

malcomio’s picture

Status: Needs review » Needs work

This would be a very useful feature, but the access check is an important point.

Also USAGE.txt should also be updated with example URLs

malcomio’s picture

The patch does seem to achieve the desired result, although I agree with the comment at #5 that it would be more robust to just use the entity ID - including titles gets messy, especially with accents and other special characters.

malcomio’s picture

Status: Needs work » Needs review
StatusFileSize
new1.57 KB

Here's a patch based on @jehon's suggestion in #7.

I've only tested it on single-value node references so far, using the node ID.

jehon’s picture

Hey, would be great to have it work with multiple values, for the sake of completelessness...

But I have no use case for the moment :-)

jehon’s picture

Hello

Who should make this code review, and how to do it ?

Could you guide me to somewhere I could find that information?

malcomio’s picture

Hi jehon - the best place for getting started is probably https://www.drupal.org/contribute/development for general information, and https://www.drupal.org/patch/review for info on reviewing patches

malcomio’s picture

Looks like multi-value fields don't work in the 7 version either, although there is a patch for it: #1468024: Impossible to prepopulate multiple values in select

jehon’s picture

Status: Needs review » Reviewed & tested by the community
jehon’s picture

Hello

I reviewed the code, and I confirm that it is working.

Thanks

pheraph’s picture

The Patch #11 is working for me, too (with single value node references).

srjosh’s picture

StatusFileSize
new3.04 KB
srjosh’s picture

This one cleans up some PHP notices.

srjosh’s picture

Status: Reviewed & tested by the community » Needs review
StatusFileSize
new3.09 KB

This one cleans up a notice that happens when you attempt to prepopulate a field that doesn't have an actual field (markup type thing). Total edge case, but found in connection with my testing.

malcomio’s picture

@srjosh - are these patches to fix issues introduced by the previous patch? if so, please could you create an interdiff? see https://www.drupal.org/documentation/git/interdiff

if they're issues that exist separate to the patch, please could you create a separate issue?

thanks

Derimagia’s picture

Status: Needs review » Needs work

"\Drupal\node\Entity\Node::load" - Reference fields don't have to be nodes. This shouldn't have any hard-codes to the entity type.

sreher’s picture

I have problems with the select type widget.

      if ($type == 'select') {
        $form['widget']['#value'][] = $request_slice;
      }

I guess it because I use no multivalue field. I limit the usage to "1", so
$form['widget']['#multiple'] = false

It works without the new added array only "$form['widget']['#value']".

      if ($type == 'select') {
        $form['widget']['#value'] = $request_slice;
      }

So we had to check the multiple value first and than decide which variant to use?

ressa’s picture

I can also confirm that the patch in #11 works with a single value node reference. It would be great to get it committed to the current dev-version. Maybe even get a D8 alpha-release?

avibrazil@gmail.com’s picture

Patch #21 works beautifully for me.

dreeds’s picture

subscribe

paddy.doyle’s picture

Patch #21 works for me too, for content with two entity references. Thanks!

juliencarnot’s picture

Status: Needs work » Reviewed & tested by the community

Patch #21 works for me too, marking this issue as RTBC!

  • jbrauer committed 96d7b48 on 8.x-2.x
    Issue #2668010 by srjosh, malcomio, juliencarnot: Prepopulate for Entity...
jbrauer’s picture

Status: Reviewed & tested by the community » Fixed

Committed. Thanks!

Status: Fixed » Closed (fixed)

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

texas-bronius’s picture

For anyone looking for it:
Just enable this module, and prefill your Drupal 8 entity reference field that looks like:

name="field_response_game[0][target_id]"

by a URL in Views constructed like:

/node/add/response?edit[field_response_game]={{ nid }}

Afaik, there's not an out of the box way of subsequently hiding that auto-populated field like nodereference_url would do.

skyredwang’s picture

@jbrauer No. this issue is not fixed, as #23 pointed out. Can you reopen?

skyredwang’s picture

StatusFileSize
new1.1 KB

Attached is the patch against the latest 8.x-2.x and fix #23

jbrauer’s picture

Status: Closed (fixed) » Needs review

Reopening for additional review.

daggerhart’s picture

Related issue #2847371: Entity reference now works only with nodes contains a working patch that accounts for single and multiple value entity reference fields for any entity_type.

colan’s picture

Please review #2849432: Simplify Prepopulate implementation with the Entity API as we're looking for more feedback, and it should also solve this issue.

hanoii’s picture

FWIW, I tried #36 and works nicely.

possibri’s picture

I was looking to test this patch but it appears the /src directory no longer contains a Controller directory, nor any of the code mentioned here. Are things changing or was that an accident?

colan’s picture

Status: Needs review » Fixed

#38 is in. Please reopen if it doesn't fix this.

possibri’s picture

@colan I am using the most recent dev version of Prepopulate but this is still an issue. I tried using the syntax as shown in the issue linked in #38, but still my Entity Reference field doesn't populate. I've tried changing the field widget to autocomplete and also checkboxes and neither work. If there is anything I might be doing wrong please point me to the proper info and I'll do my best to work it out. Thanks!

colan’s picture

Status: Fixed » Needs review

Setting status back as per #42.

Status: Needs review » Needs work

The last submitted patch, 35: prepopulate_for_entity-2668010-35.patch, failed testing. View results

edysmp’s picture

This not works. Maybe this was broken in this?

sketman’s picture

It does not work for me neither. I tryed every possible formatof url pattern but with no luck.

edysmp’s picture

Assigned: Unassigned » edysmp

Working on this.

edysmp’s picture

Assigned: edysmp » Unassigned
Status: Needs work » Needs review
StatusFileSize
new1 KB

This patch works for me with dev branch.

edysmp’s picture

use this format: ?edit[field_page]=30&edit[title]=Hello

heddn’s picture

Can we open a follow up issue for this? There's already been a commit and a very long conversation over the years.

edysmp’s picture

OK. I don't noticed. but this is working with this trick without my patch: ?edit[field_page][widget][0][target_id]=2

sketman’s picture

I can confirm that hack #52 works for me.
This prepopulates also Dynamic Entity Reference fields.
Thanks @edysmp

drupaldope’s picture

thanks sketman, can you also confirm this prepopulates entity reference fields using arguments from the URL ?
...
edit: it looks like the field has no options for prepopulate from URL like the entity reference prepopulate in Drupal 7.

heddn’s picture

There is no UI for this module. However, if the field values are prepopulated in the URL, then it will use them as prepopulated values.

heddn’s picture

Status: Needs review » Fixed

Status: Fixed » Closed (fixed)

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

maxilein’s picture

StatusFileSize
new4.46 KB

#52 isn't working for me: I have a DER (dynamic entity reference) field with different types of content:

  • user
  • content

I can set the value in the (label) reference field but I cannot select the entity_type.

There is an issue for DER with a patch, but for the very old beta version.

https://www.drupal.org/project/prepopulate/issues/2910117

maxilein’s picture

StatusFileSize
new32.08 KB

Here is the rendered output to image in #58

colan’s picture

This issue is closed/fixed. Please find/open another one if you're having problems. Thanks!

ressa’s picture

I can confirm that the new syntax (as outlined on the module page) works with entity reference fields:

http://www.example.com/node/add/page?edit[field_entity_reference][widget][0][target_id]=123

dureaghin’s picture

The new syntax doesn't work for me. But this is working with this:

http://www.example.com/node/add/page?&edit[field_entity_reference]=123

prineshazar’s picture

Example #61 & #62 didn't work for me. The following did (select field, wrapped in a container):

http://www.example.com/node/add/page?&edit[field_entity_reference][widget]=123

bwong’s picture

I can get this working when the entity reference field is not within a container.

maxilein’s picture

What container?

bwong’s picture

An Inline entity form - Complex - Table View Mode within a Details container.

maxilein’s picture

And it works without the details container?
So the IEF would be working? I never tried that.

toki’s picture

http://www.example.com/node/add/page?edit[field_entity_reference][widget][0][target_id]=123
This syntax suggested on the module page (like in #61) worked for me but only if the widget type is "Autocomplete" on your Manage Form Display. It did not work with "Autocomplete (tags style)" for example.
Hope this helps.

ledjerdemain’s picture

Sorry for being a super noob here, but I don't get how to make this work. I have

  • A content type called Incidents
  • An entity reference field to the content type "Project"
  • It's Form Display of the field is Autocomplete (In need this field to chose a project depending on the URL)
  • I have the module installed and had to apply the latest patch manually
  • I cannot get those tokens on the content add/edit form's URL

Where is that label field? How do I rewrite the add/edit form url so that shodws "node/add/page?edit[field_entity_reference][widget][0][target_id]=123"?

Thanks in advance.

ressa’s picture

I usually create a view, and add a block, to show on the content type referred to, which in this example is from a "Chapter" to an "Article". Under "Contextual filter", add "Node ID" and select "When the filter value is NOT available" > "Provide default value" > "content ID from URL".

Add the node ID field, call it for example "Prepopulated link with nid (Content: ID)". Under "Rewrite results", check "Override the output of this field with custom text" and add <a href="/node/add/chapter?edit[field_main_article][widget][0][target_id]={{ nid }}">Create chapter</a>, add the block, and only show it on Article content type.

socialnicheguru’s picture

This seems to work on autocomplete but it does not work on autocomplete (tags).

maxilein’s picture

Checkout https://www.drupal.org/project/epp
Much easier because no hassle with widget settings. Docu is great.
Had it coexist with prepopulate for a while whitout any problems.

ressa’s picture

Entity Prepopulate is great. Note that it requires the Token module to work with reference and text fields, and to show the token browser ("Browse available tokens.").