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;
  }
}
18

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

0
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;
  }
}

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.