I have a solution for you. Create a custom module and do some coding like given below. In my case my module name is comm_support
content type name is Field Depen (Machine name: field_depen)
and fields are Field A (Machine name:field_field_a)
and Field B (Machine name: field_field_b)
. Also install jQuery Update module.
Use hook_form_alter()
to define a custom form after build function.
/**
* Implements hook_form_alter().
*/
function comm_support_form_alter(&$form, &$form_state, $form_id) {
if ($form_id === 'field_depen_node_form') {
$form['#after_build'][] = '_custom_after_build';
}
}
After this implement custom after build function a add a custom js file to your node form. After adding custom js file we will pass base url to our custom js file so that we can use base url on our ajax call url parameter.
/**
* Implements custom after build function.
*/
function _custom_after_build($form, &$form_state) {
global $base_url;
$form['#attached']['js'] = array(
drupal_get_path('module', 'comm_support') . '/js/comm_support.js',
);
drupal_add_js(array('comm_support' => array('base_url' => $base_url)), array('type' => 'setting'));
return $form;
}
Now create a js file inside your_module/js/comm_support.js
and paste this code to js file.
/**
* @file
* A JavaScript file for the comm_support module.
*/
(function ($, Drupal, window, document) {
'use strict';
Drupal.behaviors.comm_support = {
attach: function (context, settings) {
// Place your code here.
$('input[name="field_field_a[und][0][value]"]').on('change', function () {
var field_a = $(this).val();
var base_url = Drupal.settings.comm_support.base_url;
$.ajax({
url: base_url + '/comm-support/get-field-b/',
type: "post",
dataType: 'json',
data: { "field_a" : field_a },
success: function (d) {
var field_b_val = field_a.split(' ');
$('input[name="field_field_b[und][0][value]"]').val(field_b_val[1] + '00' + (d + 1));
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
}
};
})(jQuery, Drupal, this, this.document);
Implement hook_menu()
for registering ajax callback path.
/**
* Implements hook_menu().
*/
function comm_support_menu() {
$items['comm-support/get-field-b'] = array(
'page callback' => '_get_field_b_value',
'access callback' => true,
'type' => MENU_CALLBACK,
);
return $items;
}
In ajax callback function fetch if Field A have exiting node with same location and get result count.
/**
* Implements callback function to fetch field A value count.
*/
function _get_field_b_value() {
$str = check_plain($_POST['field_a']);
$query = db_select('field_data_field_field_a', 'f');
$query->fields('f', array('entity_id'))
->condition('bundle', 'field_depen')
->condition('field_field_a_value', $str);
$result = $query->execute()->rowCount();
echo drupal_json_encode($result);
}
Now clear the cache and this is the complete solution.