Note: I had this problem with 'select' and 'textfield' form '#type' elements so I'm not sure if it applies to all.

In creating a ajax-enabled form element I have something like the following:

<?php
$element = array(
  '#type' => 'textfield',
  '#default_value' => '',
  '#attributes' => array('id' => 'textfield_css_id'),
  '#ajax' => array(
    'wrapper' => 'ajax_update_css_id',
    'callback' => 'MYMODULE_some_ajax_callback
  ),
);

The rest of my functions/callbacks are already in and working.

The ajax functionality works when the "#attribute => array('id' => 'SOMENAME')' is commented out.

The ajax functionality fails to work when the line remains.

I'm not sure if there is another thread on this but I wanted to point it.

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

rfay’s picture

Version: 7.7 » 7.x-dev

I confirm this. The JS code that sets up triggers seems to be dependent on the ID created by drupal_html_id().

alx_benjamin’s picture

Issue summary: View changes

Can confirm the same.

alx_benjamin’s picture

To work around this I'd add a class to the ajax element and later get its id through the class:

$form['form-name'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => $default,
    '#attributes' => array(
      'class' => array('my-class'),
    ),
    '#ajax' => array(
      'callback' => 'mymodule_some_ajax',
      'wrapper' => 'my_wrapper'
    ),
  );
(function ($) {
  Drupal.behaviors.msftaudit_audit_formxx = {
    attach: function (context, settings) {
      
      var element_id = $('.my-class').attr('id');
      
      Drupal.ajax[element_id].options.beforeSubmit = function(form_values, element, options){
	//Do what you need to do and then
	//return TRUE;
	//or
	return FALSE;
      }     
    }
  };
}(jQuery));
stevenlafl’s picture

Why is this still a fucking issue?

David_Rothstein’s picture

Status: Active » Postponed (maintainer needs more info)

To set a custom ID on a form element, you should use $element['#id'] rather than $element['#attributes']['id'].

Does that fix it? (It seems to for me.)

If so we should probably just close this issue since the #id vs. ['#attributes']['id'] thing is general to the form API (not specific to the Ajax system) and there are already other issues about making it less confusing:
#2582869: #attributes example in the form API reference should give clearer examples, including examples of when not to use it
#974502: Replace $element['#id'] with $element['#attributes']['id']

scottalan’s picture

I ran into a similar issue when dealing with links. Posting a patch here to keep this together until something better comes around.

This is just against 7.x-dev, for now.