#ajax is

used by: button, checkbox, checkboxes, image button, password, radio, radios, select, submit, tableselect, textarea, text_format, textfield

Sadly, form is not on the list. But on one form, I need to apply ajax to all form elements. With possible exception of submit button, but it will be hidden if javascript works, so it is not an issue, literally all elements is OK.

Is there any neat way to do it?

Currently I'm writing something like this:

$ajax_code = array(
  'callback' => 'poll_choice_js',
  'wrapper' => 'poll-results',
  'method' => 'replace',
  'effect' => 'fade',

And then in each element:

  '#ajax' => $ajax_code,

But it will be easy to forget to add this line to some elements in future, so I'm looking for a way less prone to errors.

Reason: My wrapper is actually outside a form and is used for preview, I need to update preview every time anything changes. Form will never need to be submitted. Ajax will never change form elements.

  • 1
    foreach (element_children($form) as $key) { $form[$key]['#ajax'] = array(...); } in a recursive function is the only way, really. I've never seen anything built in for that
    – Clive
    Jul 16 '14 at 13:19
  • @Clive Boo, I believed there must be something and I'm just missing it :/
    – Mołot
    Jul 16 '14 at 13:20
  • 2
    I don't that's a very common request, as you're adding the same ajax behavior to every element of the form I don't think there's anything that behaves that way in core or other modules I've seen.
    – pcambra
    Jul 16 '14 at 15:47

I don't believe there's anything 'built in' for that, but a small recursive function would handle it:

function _MYMODULE_apply_ajax(&$element, $ajax) {
  $element['#ajax'] = $ajax;
  foreach (element_children($element) as $key) {
    _MYMODULE_apply_ajax($element[$key], $ajax);

Where you apply this kind of depends what you need. You could add it at the end of the form function itself, but if there's a chance your form could be altered it would be best in hook_form_alter(). Either way just call

_MYMODULE_apply_ajax($form, $ajax_array);
  • Thanks. At least now I know it's not the case of me missing something.
    – Mołot
    Jul 17 '14 at 6:41

Your Answer

