function ctools_ajax_associate_url_to_element in Chaos Tool Suite (ctools) 6
Associate a URL to a form element with a hidden form.
This is a helper function to easily associate a URL with a form element which can be used for different ajax functionality.
You would call this function on a form element in the form function like this:
$form['example'] = array(
'#title' => t('Example'),
'#type' => 'select',
'#options' => array(
1 => 'One',
2 => 'Two',
3 => 'Three',
),
'#default_value' => 1,
);
ctools_ajax_associate_url_to_element($form, $form['example'], 'example/ajax/urlpath');
The AJAX request will POST the value of the form element in the "ctools_changed" parameter (i.e. $_POST['ctools_changed']).
Parameters
&$form: Reference to the form element. This is required to have the #id and #attribute elements populated and to create the hidden form element for each select.
&$form_element: The form element we are going to take action on.
$dest: The URL to associate the form element to.
$type: Optional; A type to use, in case a different behavior should be attached. If empty the type will be set to "ctools-use-ajax" for submit elements and "ctools-use-ajax-onchange" for other elements.
File
- includes/
ajax.inc, line 590 - Utilize the CTools AJAX responder.
Code
function ctools_ajax_associate_url_to_element(&$form, &$form_element, $dest, $type = '') {
drupal_add_js('misc/jquery.form.js', 'core');
if (!isset($form_element['#id'])) {
//Create a unique ID to associate $form_element and hidden elements since we dont have an ID
$form_element['#id'] = uniqid('ctools-ajax-url-');
if (empty($type)) {
$type = $form_element['#type'] == 'submit' ? 'ctools-use-ajax' : 'ctools-use-ajax-onchange';
}
if (empty($form_element['#attributes']['class'])) {
$form_element['#attributes']['class'] = $type;
}
else {
$form_element['#attributes']['class'] .= " {$type}";
}
}
//Add hidden form element to hold base URL
$form[$form_element['#id'] . '-url'] = array(
'#type' => 'hidden',
'#value' => $dest,
'#attributes' => array(
'class' => $form_element['#id'] . '-url',
),
);
}