Problem/Motivation

Today I found a disappointing fact about using '#ajax' in Forms API. When '#attributes' is defined on element that also have '#ajax' property, AJAX will not work, because HTML attributes required by Drupal AJAX engine will not be applied. It's not documented, but very confusing: I spent almost two days to figure out why my AJAX form became broken.

My AJAX form had the following definition:

$form['submit'] = array(
  '#type' => 'submit',
  '#ajax' => array(
    'callback' => 'mymodule_callback',
    'wrapper' => 'form-wrapper',
  ),
  '#attributes' => array(
    'id' => 'my-custom-id-i-needed',
  ),
);

But clicking submit button will not send request via AJAX, because Drupal in this case will not assign HTML attributes used by AJAX engine. It sees that the '#attributes' array is already defined and just skips it, causing form to work as a regular HTTP form.

Proposed resolution

I suppose Drupal must rely on '#ajax' and apply or merge required '#attributes' regardless of what provided in code to avoid this 'AJAX crush'. And of course it should be documented.

Comments

debaryadas’s picture

I find out a solution of the problem you mentioned. Actually in Drupal, there is attribute '#id' which is used to populate form element's id property internally.
In your case, you can use this attribute to set a custom id rather than that Drupal generates internally. So if you want to add a custom id then

Replace


$form['submit'] = array(
  '#type' => 'submit',
  '#ajax' => array(
    'callback' => 'mymodule_callback',
    'wrapper' => 'form-wrapper',
  ),
  '#attributes' => array(
    'id' => 'my-custom-id-i-needed',
  ),
);

With


$form['submit'] = array(
  '#type' => 'submit',
  '#ajax' => array(
    'callback' => 'mymodule_callback',
    'wrapper' => 'form-wrapper',
  ),
  '#id' => 'my-custom-id-i-needed',
);

Additionally if you want to add a class or other attributes then you can use #attributes property in the following way


$form['submit'] = array(
  '#type' => 'submit',
  '#ajax' => array(
    'callback' => 'mymodule_callback',
    'wrapper' => 'form-wrapper',
  ),
  '#attributes' => array('class' => array('my-custom-class')),
  '#id' => 'my-custom-id',
);

debaryadas’s picture

Hi,

Did the solution I provided in the above post help you?

With Regards
Debarya Das

debaryadas’s picture

Status: Active » Closed (fixed)
schmidt_nsk’s picture

Thanks, I just removed explicit definition of #attributes array, but decided to post this issue because I find this fact confusing for those people who are not aware of this stuff. I remembered this for myself, but I guess any API/code would be better if it will be hard to use it incorrectly. In other words API will be solid and easy to use if there will be no possibility to break system logic by developer..