How should I go about making my custom Drupal 7 Form element support AJAX events, just like other standard FAPI elements?
For example, with a drop-down list, I would do this:
$element['book'] = array(
'#type' => 'select',
'#title' => t('Book'),
'#options' => $books,
'#default_value' => $default_book,
'#ajax' => array(
'wrapper' => 'replace-me',
'callback' => 'replacement-callback',
'method' => 'replace',
),
);
But now that '#type' is my own custom element, the '#ajax' property is ignored. This is what I have implemented thus far:
function mymodule_element_info() {
return array(
'customelement' => array(
'#input' => TRUE,
'#process' => array('customelement_process'),
'#theme' => array('customelement'),
'#theme_wrappers' => array('form_element'),
'#tree' => TRUE,
),
);
}
function mymodule_theme($existing, $type, $theme, $path) {
return array(
'customelement' => array(
'render element' => 'element',
),
);
}
function theme_customelement($variables) {
// render some elements
return $output;
}
function form_type_customelement_value($element, $input = FALSE, &$form_state) {
// manipulate form values
return $input
}
function customelement_process($element, &$form_state, $complete_form) {
// build the compound form array
$element['#tree'] = TRUE;
$element['book'] = array(
'#type' => 'select',
'#title' => t('Book'),
'#options' => $books,
'#required' => true,
);
$element['chapter'] = array(
'#type' => 'textfield',
'#title' => t('Chapter'),
'#size' => 3,
'#maxlength' => 3,
'#required' => true,
);
return $element;
}
Using my custom element in a form goes like this:
function mymodule_menu() {
$items = array();
$items['path/to/page'] = array(
'title' => 'Test form',
'type' => MENU_LOCAL_TASK,
'weight' => 30,
'page callback' => 'drupal_get_form',
'page arguments' => array('mymodule_callback_testform'),
'access callback' => 'user_access',
'access arguments' => array('mymodule_admin'),
);
return $items;
}
function mymodule_callback_testform() {
$form = array();
$form['test_element'] = array(
'#type' => 'customelement',
'#title' => 'Custom element test',
'#required' => TRUE,
'#ajax' => array(
... // this has no effect :(
),
);
return $form;
}
But unfortunately it doesn't "magically" support AJAX. I would like to trigger a Drupal AJAX event when any sub-element of my custom element has triggered certain events.