Authored by Zishan Razzaq

Wednesday, November 23, 2011

How to use Substring in Apex Code - Force.com

Hi everyone:

Scenario:
We have a string value to be copied from one field in a Standard object to the Custom Object Standard field "Name". Yes you can do this in a formula field but if the objects are not related directly you can not.

So, a little bit about Custom Object regarding the standard field "Name".
Name field in a custom object its length is 80 MAX. No one can change the attribute on this field to go over 80 length.
So since we are utilizing code to do the update, Apex will not automatically cut off the string if it is more then 80. It will submit an error.

Solution:
We utilized substring method in Apex to accomplish anything more then 80 characters going into the name.
Substring Method - "Returns a new String that begins with the character at the specified startIndex and extends to the character at endIndex - 1." Click Here for more on String Methods

To clarify this, if we have a string such as 'ABC' length is 3 characters. If you place this in a substring and you wanted the first 2 characters, it would be 'ABC'.substring(1,3) = 'AB' ... Make it mathically easier, 3-1=2 which gets you the first 2 characters in your string.

Now the catch in code, you would need utilize the actually name of the field instead of placing it in a string.
String ProdName;

Product2 prod = [ SELECT p.ProductCode, p.Name, p.Id, 
FROM Product2 p 
WHERE p.Id =: oppLineItem.PricebookEntry.Product2Id];
 
if(prod.Name.length()>80){


//This would get the first 90 characters of the string
ProdName = prod.Name.SubString(0,80); customobject__c.Name = prodName; }
I hope this helps... 
A little lesson in code sometime does not hurt anyone.
Thanks
Zishan
Watch Me Fight 
Join My Facebook on Cage Assassin Fight Gear 
Like my fan page Cage Assassin Fight Gear