Having a simple form with few input fields. After clicking on ajax callback submit button, I'm returning the table element.
Code:
//Hypertension treatment
$form['hyper_treat'] = array (
'#type' => 'radios',
'#title' => ('Hypertension treatment:'),
'#options' => array(
'y' => 'Yes',
'n' => 'No'
),
);
//Hypercholesterolemia
$form['hyperchol'] = array (
'#type' => 'radios',
'#title' => ('Hypercholesterolemia:'),
'#options' => array(
'y' => 'Yes',
'n' => 'No'
),
);
//submit button
$form['action'] = [
'#prefix' => '<div id = "ajax_submit">',
'#name' => 'ajax_action',
'#type' => 'button',
'#value' => $this->t('Submit'),
'#ajax' => [
'callback' => '::setMessage',
'wrapper' => 'scrollable',
'method' => 'replaceWith',
'effect' => 'fade',
],
];
//table
$form['table'] = array(
'#prefix' => '<div id="scrollable" class = "col-md-8"><h4>View Data</h4>',
'#type' => 'tableselect',
'#suffix' => '</div>',
'#header' => $header,
'#options' => $options,
'#disabled' => $disabled,
'#attributes' => array('id' => 'sort-table'),
'#empty' => t('Select criteria and search data'),
);
//callback function
public function setMessage(array $form, FormStateInterface $form_state) {
$options = getOptions(); //gets the associative array
$form['table']['#options'] = $options;
return $form['table'];
}
I had issues with the pagination and sorting of the table returned using ajax. So I thought of using "Datatables" as the alternative option.
So after the callback, I would want to apply the below jquery to have the table shown as a datatable.
$('#sort-table').DataTable( {
order: [[ 1, 'asc' ]]
} );
Tried executing the 'mousedown' event for the button but the jquery executes before the ajax callback.
Is there a possible way to represent the $form['table'] element returned from the ajax callback, as a datatable?
Triggering any other event after table returned would display it as a datatable, but I'm looking to have the returned table displayed as a datatable immediately after the $form['table'] is returned. This happens only when the jquery snippet is executed immediately after the table element is returned from the ajax callback function.
Drupal.behaviors.myBehavior
object and attach it as library. On each ajax request the Drupal behaviors are run again, with the context limited to the newly loaded content.