I want ajax dependent fields in one of my node's form so I am altering the form.

here is the code

    function mymodule_form_alter(&$form, &$form_state, $form_id) {
      $selected_first = isset($form_state['values']['field_first'][LANGUAGE_NONE][0]['nid']) ? $form_state['values']['field_first'][LANGUAGE_NONE][0]['nid']: '0';
    $form['field_first'][LANGUAGE_NONE]['#ajax'] = array(
      'callback' => '_first_callback',
      'wrapper' => 'second-field-wrapper',
    $form['field_first'][LANGUAGE_NONE]['#default_value'] = $selected_first;

    $form['field_second'][LANGUAGE_NONE]['#prefix'] = '<div id="second-field-wrapper">';
    $form['field_second'][LANGUAGE_NONE]['#suffix'] = '</div>';
    $form['field_second'][LANGUAGE_NONE]['#options'] = _get_second_options($selected_first);
function _first_callback($form, $form_state) {
  return $form['field_second'];
 * Ajax callback for second field
function _get_second_options($occ_id) {
  //array which contains some int values
  return $second_options;

Some more information: field_first is select list of type node reference and field_second is checkboxes.

Issue: This works fine while creating the node. But when I edit the same node, the second field doesn't show and also values selected for this field while creating the node are also not checked by default.

1 Answer 1


You can try to use this module https://www.drupal.org/project/dfv

  • Thank you smile for the suggestion, but this is not working out form me because I have two fields which are dependent on first_field.
    – ruby
    Sep 3, 2014 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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