2

I have a form like this:

$form['my_button'] = array(
  '#type' => 'button',
  '#ajax' => array(
    'callback' => 'my_callback_1',
    'wrapper' => 'some_wrapper',
  )
);

Which works fine (code is very simplified). Now, in the callback, I want to return another button, which also has ajax configured:

function my_callback_1() {
  return array(
    'my_other_button' => array(
      '#type' => 'button',
      '#ajax' => array(
        'callback' => 'my_callback_2',
        'wrapper' => 'some_other_wrapper',
      )
    ),
  );
}

function my_callback_2() {
  return array('#markup' => 'success!!');
}

Now, when I click on the first button, Drupal loads the second button just fine. The problem is, a click on the second button does nothing. Am I missing something?

0

After a lot of reading, I solved this by returning $form on the AJAX callback, and including the second button on a form rebuild. My code now looks more like this, and it's working fine:

function my_form($form, &$form_state) {
  $wrapper_id = drupal_html_id('some_wrapper');

  $form['#prefix'] = '<div id="' . $wrapper_id . '">';
  $form['#suffix'] = '</div>';

  if (isset($form_state['my_flag']) && $form_state['my_flag']) {
    $form['my_other_button'] = array(
      '#type' => 'button',
      '#name' => 'my_other_button',
      '#ajax' => array(
        'callback' => 'my_callback',
        'wrapper' => $wrapper_id,
      )
    );
  }
  else {
    $form['my_button'] = array(
      '#type' => 'submit',
      '#name' => 'my_button',
      '#ajax' => array(
        'callback' => 'my_callback',
        'wrapper' => $wrapper_id,
      ),
    );
  }
}

function my_form_submit($form, &$form_state) {
  switch ($form_state['triggering_element']['#name']) {
    case 'my_button':
      //code for when user presses the first button
      $form_state['my_flag'] = TRUE; //show the other button
      $form_state['rebuild'] = TRUE; //this is necessary!
      break;
    case 'my_other_button':
      //code for when user presses the second button
      break;
  }
}

function my_callback($form, $form_state) {
  return $form;
}

I think the problem had to do with a button being outside an actual form. I hope this helps others...

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.