Recently I was asked to put a trigger together that copied a Long Text Area value that can hold up to 32,000 characters to a Text Area field that can only hold up to 255 characters. Naturally when you try to copy a value larger than 255 characters to a Text Area field an error will be thrown. So I had to figure out how to basically truncate a string value to 255 characters in order to assign it to a Text Area field.
The string method 'substring' does the trick! What is does is much like in excel using the left(), mid() and right() formulas you give it a starting place and tell it how many characters to grab. Salesforce's basic example is as follow:
'hamburger'.substring(4, 8); // Returns "urge" 'smiles'.substring(1, 5); // Returns "mile"
My problem was a bit more complex as I had to include logic that would say only perform this truncation when the Long Text Area value is larger than 255 characters. If you try to truncate a string value using substring to a length longer than the string itself you will get an error. Here is the code I used for this instance.
string EX1 = Sample.LongTextArea1__c; string EX2 = Sample.LongTextArea2__c; //Get sizes of Goal and Strategy in the event they are longer than 255 char and need to be truncated Integer size1 = EX1.length(); Integer size2 = EX2.length(); //If Goal or Strategy are longer than 255 characters they need to be truncated if(size1> 255){ EX1= EX1.substring(0, 255); } if(size2 > 255){ EX2 = EX2.substring(0, 255); }
I retrieve the length of the strings that were assigned the value of the Long Text Area (EX1 and EX2) and if those lengths are more than 255 characters then I truncated it with the substring method. If they are shorter than the maximum length of a Text Area (255) I do not adjust them at all.
Below is a link to the String Methods as defined by Salesforce.com.
http://www.salesforce.com/us/developer/docs/apexcode/index.htm
THANK YOU!
ReplyDelete