0

following snippet doesn't set the default value.

 $form['field_image']['#default_value']='default';

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.

7

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);

Cheers!

  • 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
0

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.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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