+ Start a Discussion
Ker Vin.ax1237Ker Vin.ax1237 

ISBLANK in apex trigger

I wanted to create a trigger that basically copies the first 50 characters of the Comments field in Task to a custom field. It looks kinda like this

 

for (Task tasksToUpdate: trigger.new){
Integer max=tasksToUpdate.Description.length();
if (max != 0) {
Integer endCharacter = 0;
if (max < 50)
endCharacter = max;
else
endCharacter = 50;
tasksToUpdate.Comments_Short__c = tasksToUpdate.Description.substring(0,endCharacter) ;
}
}

All well and good, but when I try to execute this with a blank Comments field, the error "execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object" shows up. I think I'm supposed to have a catch-exception when it is blank/null, but I can't understand why this doesn't work. Any ideas?

Best Answer chosen by Admin (Salesforce Developers) 
JaggyJaggy
for (Task tasksToUpdate: trigger.new){
if(tasksToUpdate.Description != null) {
Integer len = tasksToUpdate.Description.length();
String s = tasksToUpdate.Description;
if(len > 40) {
s = tasksToUpdate.Description.substring(0,40);
}
tasksToUpdate.Comments_Short__c = s;
}


}

 try above

All Answers

JaggyJaggy
for (Task tasksToUpdate: trigger.new){
if(tasksToUpdate.Description != null) {
Integer len = tasksToUpdate.Description.length();
String s = tasksToUpdate.Description;
if(len > 40) {
s = tasksToUpdate.Description.substring(0,40);
}
tasksToUpdate.Comments_Short__c = s;
}


}

 try above

This was selected as the best answer
Ker Vin.ax1237Ker Vin.ax1237

It works, thanks! I was expecting it to be a method or something, shows how much I have to learn ^_^;