I have an inventory management system I am working on and I have the need to let users input values to be created into inventory. These values consist of numbers that are used as the name for the inventory object. I have a workflow that takes the name and populates it into a unique field to assure that no duplicates can enter the system. This works as it should.
When they are entering the numbers into the fields I am batching these numbers together so that they can create multiple inventory items in one pass. My issue is that I have been unable to find a way to get the Value of the field that is causing the DUPLICATE_VALUE. I see that I can get the field name but I would like to be able to show them exactly which Inventory Number is the one that caused the issue so they can go in an correct that specific one. I also realize that I can get the ID of the object that caused the error but this is an insert of new objects so I would not be able to query for the information after the DML failed.
Does anyone know of a way to get the value of the field that failed a uniqeness check upon insert of an object?
Thanks in advance!
Edit 1: Was asked to clarify a little bit.
When inserting a set of SObjects - I am wanting a DML Exception to be thrown when a duplicate value is found. This is working correctly. I need to be able to show the Value of the field that caused the duplicate check to fail. For example:
try{
insert account;accounts;
/// Am inserting over 3000 accounts in this scenario
}
catch(DmlException de){
system.debug(de.getMessage());
ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.FATAL,
'A Duplicate Value was found.'+
'That value is: '
// I NEED A WAY TO GET THE VALUE THAT CAUSED THE ERROR HERE);
ApexPages.addMessage(msg);
}
To elaborate further - If I am inserting 5 accounts and the accounts object has a unique field of "Account_Number__c". If one of these accounts I am inserting fails because the value of "Account_Number__c" was "123" and "123" already exists as a value for "Account_Number__c" on another Account record - I would like to get the value of "123" out of the DML Exception so I can return it to the user.
Edit 2: I tried the solution put out by one of the commenters and I was unable to get the Id of the record that has the value already. making a call to getDMLId(0) returns the Id of the record that failed to insert - which is null. I can parse the getMessage() response as I see that the ID is inside of this message but I would rather have a more stable way of getting this ID if possible. Any ideas?