Hey all,
As I can’t imagine this wouldn’t be something that many people are interested in, I figured I’d post my solution for adding an auto-increment field to any given module. The following examples apply to the accounts module. Here’s how I did it:
1. Add new field via studio
I added an integer field via studio called “public_id” (which is then called public_id_c by SuiteCRM after saving)
You’ll want to turn off inline-editing for this field!
2. add logic_hook.php (or other name) to /custom/Extension/modules/[module]/Ext/LogicHooks/
-> create folder “LogicHooks” if missing)
Here’s my code:
<?php
$hook_version = 1;
$hook_array = Array();
$hook_array['before_save'] = Array();
$hook_array['before_save'][] = Array(1, 'Auto-increment für public ID Firma', 'custom/modules/Accounts/accounts_public_id_calc.php','Accounts_Public_ID','Autoincrement');
?>
3. Add autoincrement script to folder /custom/module/[module]/
I named mine “accounts_public_id_calc.php”. Important is that it matches what was define under step two above!
Here’s my script that gets fired each time I save an account record.
<?php
// 20.1.16 JD: calculate autoincrement public id field (accounts and contacts)
//
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
class Accounts_Public_ID
{
function Autoincrement($bean, $event)
{
$public_id_bean = $bean->public_id_c; // fetch public_id of this record (bean)
if (!$public_id_bean) { // if public-id is empty (empty string), set a new one, else do nothing
$start_number = 311000001; // if no public_id has been set in database for any account, use this lowest number
// query database, find largest public_id set for any account
$query = "SELECT MAX(`public_id_c`) FROM accounts_cstm";
$results = $bean->db->query($query, true);
$row = $bean->db->fetchByAssoc($results);
$public_id_max = $row['MAX(`public_id_c`)'];
if ($public_id_max > 311999998) { // if ID numbers become too large set id to "0" (obvious that something is wrong!)
$next_id = 000000000; // "0" creates database failure for some reason!
$GLOBALS['log']->error('All account-id numbers used up (311000001 to 311999999)! Please define new numbering scheme'); // suitecrm.log entry if numbers are used up.
} else if ($public_id_max) { // if public_id has been set (not an empty string) for at least one record, set the public id for this record to the max number + 1
$next_id = $public_id_max + 1;
} else {
$next_id = $start_number; // if all public_ids (for all account records) are empty, restart at start-number
}
$bean->public_id_c = $next_id; // write next_id to public_id_c field
}
}
}
?>
Please let me know what I could do better! Total PHP newbie here… First draft really. Not a lot of checks and balances… Use at your own risk!
Also if anybody knows how to easily create an alert for the user (in this case, when the numbers run out for the public id field), please let me know!