2

How can I have a computed field (field B) that has an auto-incremental number but based on the value of another field (field A).

For example: I create a node with value "Location X" in field A. Field B should get value X001, I create a second node with value "Location Y" in field A. Field B should get value Y001. I create a third node with, again, value "Location X" in field A. Field B should get value X002. And so forth

1

Checkout hook_node_presave() here you can set the values dynamically. And variable_get() and variable_set() for the increment.

With str_pad() you can add the starting zeros to the increment.

hook_node_presave($node) {
  if ($node->field_A[LANGUAGE_NONE][0]['value'] == 'Location X') {
    $increment = varibable_get('LocationX_increment', 0);
    $increment++;
    $node->field_B[LANGUAGE_NONE][0]['value'] = 'X' . str_pad($increment, 3, '0', STR_PAD_LEFT);
    variable_set('LocationX_increment', $increment);
  }
}

You don't need to save the node in this hook, just change the value of the field.

0

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.

0

You could try Rules and PHP to get this done. After a node is created, execute some PHP code where you query the database and count the number of nodes with the same Field A value (using a token for the current value of the node saved). Then you get your auto-increment value (eventually stored in an hidden field as "Location number"). You may modify the display with sprintf() to get your leading zeros. Then you add a second Rules action to set a data value and create your field B value as field A value token + Location number token.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.