This module has made entity selection so much easier!
But I have run into one issue: I can't figure out how to use hook_form_alter() to auto-populate the entity reference field's #default_value. I have a custom module that looks for input from the URL query string, and automatically plugs an entity ID into the field so that it is already selected when you view the new form. I can get this to work with all widgets except Entity Reference View Widget.
I found entityreference_view_widget_rows() - can I use this in hook_form_alter() to populate the field? The part I am unsure of is how to load the $settings argument to pass into that function.
I have looked into the Entity Reference Prepopulate module, but it appears to be more than I need right now, so I'm hoping to solve this in my custom module myself.
Thanks for the help!
Comments
Comment #2
m.stentaOk, so I got it to work, but I'm not sure if it's the "right" way to do it.
I did not use entityreference_view_widget_rows() - instead I just used it as a guide and defined my own array. It looks something like this:
I did some testing and I think those are all the necessary array elements to get it to work. I left out some, but it seems to work without them. I discovered that "#return_value" is absolutely necessary, otherwise if you add another entity to the list, your original prepopulated one gets replaced with something else.
Comment #3
akolahi commentedYour solution worked for me. Thanks.
Comment #4
vistree commentedHi m.stenta,
thank you for your suggestion. Is it correct to use the $field_value in a form_alter?
E.g. by setting
$form['field_entityref_user']['und'][0]['target_id'] = $field_value ??
In this case I think we also need to check if this value is already set, correct?
E.g.
Comment #5
m.stenta@vistree, yes - below is the actual code that I used in hook_form_alter(). Note that I am using a custom entity type called
farm_assetand the actual entity variable is stored in$asset. I am prepopulating a field calledfield_farm_asset.Also note: the
continue;line is there for me because this code runs in a foreach loop to prepopulate multiple entities in the form.Hope that helps!
Comment #6
vistree commentedThanx ;-)