Skip to content

Instantly share code, notes, and snippets.

@msztandarski
Last active December 18, 2015 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msztandarski/5846664 to your computer and use it in GitHub Desktop.
Save msztandarski/5846664 to your computer and use it in GitHub Desktop.
populating two auto-incrementing fields in same Object (workaround) The problem has been described here http://salesforce.stackexchange.com/questions/13016/how-do-i-populate-two-auto-incrementing-fields-in-same-object
/* assumptions:
CustomObj1__c contains the following fields:
DocumentType__c (picklist values: TypeX, TypeY)
seqX_ref__c (lookup reference to the object seqX__c with autonumber field)
seqY_ref__c (lookup reference to the object seqY__c with autonumber field)
receipt_id__c formula:
CASE(TEXT(DocumentType__c),
'TypeX', seqX_ref__r.DocX_num__c,
'TypeY', seqY_ref__r.DocY_num__c,
'')
seqX__c object contains: DocX_num__c autonumbered field
seqY__c object contains: DocY_num__c autonumbered field
drawbacks:
AutoNumber is not guaranteed to be continuous i.e. when inserting CustomObj1__c
and error occurs you'll see gaps in the sequence.
*/
trigger CreateSequence on CustomObj1__c (after insert)
{
Savepoint sp = Database.setSavepoint();
try
{
List<CustomObj1__c> recordsOfTypeX = new List<CustomObj1__c>();
List<CustomObj1__c> recordsOfTypeY = new List<CustomObj1__c>();
Set<id> justInsertedObjectsIds = Trigger.newMap.keySet();
List<CustomObj1__c> justInsertedObjects = [SELECT DocumentType__c, seqX_ref__c, seqY_ref__c
FROM CustomObj1__c WHERE id IN :justInsertedObjectsIds
FOR UPDATE];
// separate records by doc types
for (CustomObj1__c newObj : justInsertedObjects)
{
// collect all TypeX records
if (newObj.DocumentType__c == 'TypeX') { recordsOfTypeX.add(newObj); }
// collect all TypeY records
else if (newObj.DocumentType__c == 'TypeY') { recordsOfTypeY.add(newObj); }
}
// create seq records for each TypeX records
Map<id, SeqX__c> seqX = new Map<id, SeqX__c>();
for (CustomObj1__c txrec : recordsOfTypeX)
{
seqX.put(txrec.id, new SeqX__c());
}
insert seqX.values();
// create seq records for each TypeY records
Map<id, SeqY__c> seqY = new Map<id, SeqY__c>();
for (CustomObj1__c tyrec : recordsOfTypeY)
{
seqY.put(tyrec.id, new SeqY__c());
}
insert seqY.values();
//throw new ForcedException();
// assign inserted seq objects
for (CustomObj1__c txrec : recordsOfTypeX)
{
txrec.seqX_ref__c = seqX.get(txrec.id).id;
}
update recordsOfTypeX;
for (CustomObj1__c tyrec : recordsOfTypeY)
{
tyrec.seqY_ref__c = seqY.get(tyrec.id).id;
}
update recordsOfTypeY;
}
catch (Exception ex)
{
Database.rollback(sp);
ApexPages.addMessages(ex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment