Take the 2-minute tour ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

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"

share|improve this question
    
It's more proper to use the LANGUAGE_NONE constant than 'und'. –  chx May 8 '12 at 11:25

2 Answers 2

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)";
}
share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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