Drupal: Using #ajax on a form

This CodeLet will ajaxify the respective element and will trigger an event. Respective action will be taken by the code and displayed on the form within the specified wrapper

CodeLet: 

/**
* Implementation of hook_form_alter
*
* @param unknown $form
* @param unknown $form_state
* @param unknown $form_id
* @author DrupalD http://twtitter.com/DrupalD
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
switch($form_id) {
case 'incident_form_node_form':
$form['client_er'] = array(
'' => 'item',
'' => t('Client\'s Email Recipients'),
'' => t('Once you select a client, you will see the email recipient for that client listed here'),
'' => -49,
);

$form['field_client']['und'][''] = array(
'callback' => '_mymodule_recipitn_js',
'wrapper' => 'edit-client-er',
);
}
}

/**
* _mymodule_recipitn_js
*
* Return email recipint
* @author DrupalD http://twtitter.com/DrupalD
*/
function _mymodule_recipitn_js($form, $form_state){
$am__recipient = array();

//Get the selected client
$sn__client_nid = $form_state['triggering_element'][''];

//Find all the email recipints for that client
$am__recipient = _get_node_email_recipient($sn__client_nid);

if (!empty($am__recipient)) {
$form['client_er'] = array(
'' => 'item',
'' => implode('', $am__recipient),
'' => t('Client\'s Email Recipients'),
'' => t('Here are all the email recipients from selected client.
If you do not add any new email recipints in field below, above details will be used for this incident', array('' => t('Email Recipients'))),
'' => '',
'' => '',
);

return array(
'' => 'ajax',
'' => array(
ajax_command_replace("-client-er", render($form['client_er'])),
),
);
}
else {
return t('No email recipients found for this client');
}
}

/**
* _get_node_email_recipient
*
* @param unknown $sn__client_nid
* @author DrupalD http://twtitter.com/DrupalD
*/
function _get_node_email_recipient($sn__client_nid) {
$result = db_select('field_data_field_email_recipients', 'fer')
->fields('fer', array('field_email_recipients_email'))
->condition('entity_id', $sn__client_nid, '=')
->execute();
while ($am__email_recipient = $result->fetchAssoc()) {
$am__recipient[] = $am__email_recipient['field_email_recipients_email'];
}
return $am__recipient;
}

Drupal Ajax form Event

By DrupalD on Sat, 04/04/2015 - 1:16pm

Add comment

Log in or register to post comments
QR code for this page URL This page URL
Feedback