following snippet doesn't set the default value.


I Have content type called image and I'm trying to set the default value for a reference to it in another content type. The above code doesn't work. Printing out the form variable doesn't make it seem like an easy task.

closed as too broad by kiamlaluno Jul 9 at 6:44

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.


You need to first check the structure of your form. Mine worked with the following:

$form['field_image']['widget'][0]['target_id']['#default_value'] = \Drupal\node\Entity\Node::load(2);


  • How to check structure of the form :) ? – 1kenthomas Oct 14 '17 at 16:05
  • 1
    You can either use a devel module's function (dsm() or dpm()) or an IDE with a debugger. The debugger's breakpoint or the devel functions can be placed inside your own implementation of hook_form_alter() or directly inside the drupal_prepare_form() function. – Stefanos Petrakis Oct 14 '17 at 17:19
  • Hmm. Great for D7, it's a protected object in D8 and doesn't seem to kint() to that level. (A debugger might work). Trying to find a workable way to look at $form in D8, right now. P.S. apologies that I may have thought this was a D8 thread ... – 1kenthomas Oct 14 '17 at 19:29
  • UPDATE: you can $var=$form_state['variable'] then kint($var). – 1kenthomas Oct 14 '17 at 19:48
  • It's a D8 thread, my bad, thought it was D7. – Stefanos Petrakis Oct 14 '17 at 21:19

I had trouble with the above on 8.6.1 when using the Entity browser widget - looking at the form edit values I found that this worked for me:

      $form['field_business_partner']['widget']['target_id']['#default_value'] = 'node:18';

Simple string. Note it didn't display the requisite node in the field but as this was being programmatically set it didn't matter in my use case.


You have to set three things, 1 - node default value, 2 - Entity browser default value , And 3 - Item , Which will show in edit form, Without Assigned the items it's not displayed in entity browser, While in backed it is set when we check by kint() var, demo code in my case:

    $form['field_related_stories']['widget']['target_id']['#default_value'] = "node:25507";
    $form['field_related_stories']['widget']['entity_browser']['#default_value'] = Node::load(25507);
    $form['field_related_stories']['widget']['current']['items'] = array();

Not the answer you're looking for? Browse other questions tagged or ask your own question.