5

I have a form updating with AJAX on select element change. Easy so far. The problem is that I need to return the form & also an ajax command at the same time.

If I need the form, I just return the $form array and if I need to return an ajax command I use return array('#type' => 'ajax', '#commands' => $commands);. Both works just fine.

The problem is that I don't get it how to combine both of them in the same return object.

Any ideas how can I do that?

  • Check "Ajax Comments" contributed module you will get all the information there. – Mohammad Anwar Jun 8 '12 at 10:32
  • it's not what I need. in ajax comments they return the whole rendered form. I need to return just part of an existing form... – Marius Ilie Jun 8 '12 at 10:44
2

As a backup solution, I'll do it this way:

$form['#suffix'] = '<script type="text/javascript">some_function_to_do_what_i_need();</script>';
return $form;

this should work.

  • 1
    did you find a better solution eventually? – Bulat Apr 9 '13 at 20:48
  • Why wouldn't you just use $form['#attached']['js'][] = drupal_get_path('module', 'my_module') . '/js/functionality.js'; return $form;? – mbomb007 Apr 26 '19 at 15:55
1

You have to pass to drupal_render() the form array, then add it to your $commands as an AJAX command. You should use code similar to the following one.

function my_ajax_form_callback($form, &$form_state) {
  $new_state = array();
  $new_state['build_info'] = $form_state['build_info'];
  $new_state['rebuild'] = TRUE;
  $new_state['values'] = array();
  $new_state += form_state_defaults();

  $new_form_array = drupal_rebuild_form('my_ajax_form_id', $new_state);
  $new_form = drupal_render($new_form_array);

  $commands = array();
  $commands[] = ajax_command_html('#form-container-element-id', $new_form);

  return array('#type' => 'ajax', '#commands' => $commands);
}
  • I need to return just part of the form, not the whole rebuild, rendered form. – Marius Ilie Jun 8 '12 at 11:05
  • Then render the form element and pass it as an ajax command. Same principle I guess. – Beebee Jun 8 '12 at 11:11
1

I would use hook_ajax_render_alter(&$commands) e.g.

function myModule_ajax_render_alter(&$commands) {
  $commands[] = myModule_custom_command('hi');
}

See the documentation for details.

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.