15

I have a trigger where i am assigning ID to a cusotm field like below -

D.customfield__c = acc.Id;

The ID is coming as 00P28000000EwpjEA0

But i need only 00P28000000Ewpj 15 char. Is there is a way to use substring in apex trigger. I can't use formula field.

2 Answers 2

22

All you need to do is convert the Id to a String and you can call substring(startIndex, endIndex) on it.

The following should work:

D.customfield__c = String.valueOf(acc.Id).substring(0, 15);
8

Following Spring '21 release, we can now use a dedicated function on the System.Id class called to15().

From the documentation:

Convert an 18-character Id value to a 15-character case-sensitive string. Use the to15() method in the System.Id class. This method uses the case-sensitivity checksum in the 18-character Id value to fix any mangled casing and returns a 15-character case-sensitive string.

Example:

    String Id_15_char = '0D5B000001DVM9t';
    String Id_18_char = '0D5B000001DVM9tkAh';
    ID testId = Id_18_char;
    System.assertEquals(testId.to15(),Id_15_char);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .