10

In Drupal 6, we could use PHP to set default values, but the same code cannot be used with Drupal 7.

I am trying to do this through hook_form_alter(), but the code doesn't work.

function my_form_alter(&$form, &$form_state, $form_id) {
  dsm($form);

  switch($form_id) {
    case 'accounts_node_form':
      $form["field_accounts"]["und"]['#default_value'] = $default;
      // …
      break;
  }
}
17

Assuming that your form alter function is actually running (which you can confirm with that call to dsm()), there are actually 2 more levels of array you need to go down to in order to get to the field element:

$form["field_accounts"][LANGUAGE_NONE][0]['value']['#default_value'] = $default;

In Drupal 7 you have a an array of values for each language the field has been translated into (so that fields with multiple/unlimited cardinality can be catered for), and under each of those is in array for the various different field columns. In the majority of cases this will be 'value' but not always (for example an image field has a file id column, alt column etc)

Hope that helps

  • It is one more depth :) $form["field_accounts"]["und"][0]["value"]['#default_value'] = $default; – giorgio79 Feb 5 '12 at 10:26
  • 2
    This answer won't work for all widgets; depends on how they specify their value. For example, with an entityreference field, use: $form['field_name']['und'][0]['target_id']['#default_value'] = $default – Renee Apr 23 '13 at 0:03
  • @Renee Very true; there's a more in-depth explanation here – Clive Apr 23 '13 at 0:09
  • 1
    Field values always have a language @Mouneer, if you don't have a multilingual site the default LANGUAGE_NONE should be used – Clive Oct 4 '15 at 12:59
  • 1
    Indeed, I could have explained that a bit better @Mouneer :) You'll find the current language in the form somewhere (I think maybe $form['#entity']->language but I'd have to check, so that can be used in place of a constant. Retrieval code would also use the current language as determined by the $language global, but there are API methods to help with that anyway (field_get_items or even better the EntityMetadataWrapper provided by the entity module) – Clive Oct 4 '15 at 13:41
0

This correct:

function my_form_alter(&$form, &$form_state, $form_id) {
  dsm($form);

  switch($form_id) {
    case 'accounts_node_form':
      $form["field_accounts"][LANGUAGE_NONE][0]['value']['#default_value'] = $default;
      // …
      break;
  }
}
0

This works fine:

function my_form_alter(&$form, &$form_state, $form_id) {
  dsm($form);
  switch($form_id) {
    case 'accounts_node_form':
      $form["field_accounts"]["und"][0]['value']['#default_value']=$default;
      break;
  }
}

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.