Score:1

How to set default value on Select2 Autocomplete via hook_alter

nl flag

What's the best way to set a default value to a Select2 autocomplete field widget on form load (I'm using a reference view to populate options). I've tried a ton of different variations from within form_alter with no success, such as...

$form['field_name']['widget']['#select2']['id'] = 12

I can set the hidden <select> element with...

$form['field_name']['widget']['#default_value'] = 12

...but this value doesn't populate into the Select2 Widget.

I've combed through docs and issues without finding a solution. What am I missing?

Score:2
gb flag

With the select2 widget the #default_value' is an array so try with

 $form['field_name']['widget']['#default_value'] = [12];

It will work!

nl flag
I appreciate the response. Unfortunately as i mentioned above, this only populates the hidden <select> element and not the actual Select2 Autocomplete field. Any other tips?!?!
berramou avatar
gb flag
i have tested it on select2 widget what you mentioned above is only 12 as integer not array *[12]* as it in my answer add **[]** it will work
nl flag
Thank you for the reply - you are totally correct. I added some custom code previous to render the dropdown's HTML... and that messed things up. My bad ;)
berramou avatar
gb flag
you are welcome, i'm glad that helped
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.