5

I have a form with an entity reference field and I need to add a default value. I've tried

$form['field_op_product']['und'][0]['target_id']['#default_value'] = $product_node->nid;

but, that doesn't work. Any idea on how to do this?

The widget type is "AutoComplete"

  • It's more proper to use the LANGUAGE_NONE constant than 'und'. – user49 May 8 '12 at 11:25
6

From the sample code given in question, I assume the hook_form_alter() is used. You should first load the referring node, get the Node Title and Node ID from it, and then set the default value using both. This works.

Setting the default value using Node ID alone will not work.

$entity_node = node_load($nid);
if ($entity_node) {
    $form['field_op_product'][LANGUAGE_NONE][0]['target_id']['#default_value'] =
        "$entity_node->title ($entity_node->nid)";
}
  • Any suggestion how to do this in D8? – Justme Aug 17 '18 at 6:45
  • I tried "$node->get('title')->value ($node->get('nid')->value)"; but it is not working.. – Justme Aug 17 '18 at 6:49
  • 1
    Solved by just replaced "$entity_node->title ($entity_node->nid)"; with $node object which is $node = \Drupal\node\Entity\Node::load($nid); – Justme Aug 17 '18 at 6:51
1

Do you need a default value to be shown the user when the form is first shown?

  • If you ment this ... you set the #default_value FAPI element using hook_form_alter() (or when you build your form) in a custom module to the $id of the entity/node you want as the default selected option.

Or if you wanted a default value supplied to the database when the form is submitted (and no answer was ever given)?

  • If you meant this, then your code could be placed with your forms _validate function to supply a default value if none was given.

EDIT: since its "autocomplete" you may need to supply a #value as well if you want to change how the form is initially shown. I'm not sure on that.

0

For drupal 7.54 I found that none of the above worked for single USER entity reference field. My solution needed this code:

$form['field_user'][LANGUAGE_NONE]['#default_value'] =
    "$user->name ($user->uid)";

This might be due to the fact that only one entity can be set to the field (no multifield) and it is a user field. Here so that someone else needs less debugging than me.

  • For checkbox: $form['field_user'][LANGUAGE_NONE]['#default_value'] = $user->uid; – reptilex Feb 9 '17 at 11:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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