0

I have a "Merchant" content type created for a web site. The Merchant content type has a select field called "City" and a text field "Locality".

I want to create a "merchant_code" field that has to be something like "AB-XY-0001" where AB is first two letters of the City Name and XY is first two letters of the Locality Name and 0001 must be an incremental number, so Merchants of ABCD City and XYZ locality will have each a different code:

"AB-XY-0001",
"AB-XY-0002",
"AB-XY-0003"...
"AB-XY-9999",
etc.

And Merchants of PQRS City and LMN locality will have each a different code:

"PQ-MN-0001",
"PQ-MN-0002",
"PQ-MN-0003"...
"PQ-MN-9999",
etc..

I see that there is a Serial module, but that module helps me only creating autoincremental numbers for each content type, not based on other fields of that content type.

If I create Merchant "AB-XY-0001" and then create another Merchant of City PQRS and Locality LMN, it will have "PQ-LM-0002" code, and not "PQ-LM-0001" code.

Please help me achieve this.

Akash
  • 1
  • 2

1 Answers1

0

I coded something to give you an idea of what I would do. I have not tested it but I think it should be enough to give you an idea.

<?php
static $auto_generate = array(); // keep track of which codes are at what number
$code = '';
$code .= $node->field_city[0]['value'] . '-';
$code .= $node->field_locality[0]['value'];
if($auto_generate[$code])
{
  $auto_generate[$code]++;
}
else
{
  $auto_generate[$code] = 0;
}
$code .= '-' . $auto_generate[$code];
$node->field_merchant[0]['value'] = $code;
?>
Joel Johnson
  • 134
  • 7
  • I am not sure if this is the right way. It is always better to use the database auto-increment feature to make sure that there are no duplicates created under load. – Gokul N K Mar 28 '16 at 12:27
  • @GokulNK I dont know how you would go about that within the confines of drupal content. I assume you would have to make your own content system. Id love to see an answer with how you would go about doing that. – Joel Johnson Mar 29 '16 at 15:48