Adding autoincremental number / date / unique number to name


There is a question that pops up on the forum from time to time and it is related to methods to add your own sequential number to the records names or somewere else.
There are many ways to do it but I would like to give you a sample on how to achieve it by using current date (YYYYMMDDhhmmss) obtained via query. That way you make sure number is unique and auto incremental and without to much work.

This method consists of using a before_save logichook and a simple query at the time of record creation. (You can modify it according to your needs…)

In this sample I will utilize the Cases module. Here we go:

  1. Let’s create file CasesCreateNameHook.php under /custom/modules/Cases/hooks/ (please create folder if it doesn’t exists) and we enter the following code:
 * LogicHook Sample created By BrozTechnologies     *
 * to demostrate a simple way to add YYYMMDDhhmmss  *
 * to record's names (or were ever it's needed)     *
 * 20201006 -              *
//prevents directly accessing this file from a web browser
if (!defined('sugarEntry') ||!sugarEntry) die('Not A Valid Entry Point');

class CasesCreateNameHook
	// function called in the before_save hook
    function customName($bean, $event, $arguments)
		global $db; // These allows us access to the DB connection 
		if ($bean->id !=  $bean->fetched_row['id']) ){  // Making sure it's called on creation only			
			$query = "SELECT NOW() as currentDTime";			// using this query to calculate current date and time that is returned as string 
			$result = $bean->db->query($query, true); 
 			$row = $bean->db->fetchByAssoc($result);
            $bean->name = $bean->name.'_'.preg_replace('/[^0-9]/', '', $row['currentDTime']));  //Here we add the formated date to the name entered by the user. Please notice how we remove any character from the returned date string and leave numbers only

  1. Lets create/modify file /custom/modules/Cases/logic_hooks.php and we add our logichook definition. In our case we will use a before_save logichook like this:
// Do not store anything in this file that is not part of the array or the hook version.  This file will	
// be automatically rebuilt in the future. 
$hook_version = 1; 
$hook_array = Array(); 
// position, file, function 
$hook_array['before_save'] = Array(); 
$hook_array['before_save'][] = Array(1, 'customName', 'custom/modules/Cases/hooks/CasesCreateNameHook.php','CasesCreateNameHook', 'customName'); 

  1. Finally we run a QR&R before testing our code.

Now when creating a new Case the name should be similar to: Yourcasename_20201006172933