Salesforce Apex: Count Number of Line Breaks in Text Field

2.6k views Asked by At

I'd like to create a trigger and/or class that counts the number of line break in a longtext field in Salesforce.com.

Will this logic work if I change the debug message to instead write the commentsLength to a custom field?

public with sharing class TaskCommentsCount {
Integer commentsLength = 0;

for(Task t : [Select Comments From Task]){
List<String> lines = t.Comments.split('\n');
commentsLength += lines.size();
}

system.debug('Comments lines: ' + commentsLength);

}
2

There are 2 answers

0
eyescream On BEST ANSWER

How old your trigger / class is? Some time this year (Spring'13 release?) The String class received major upgrade and we have now the countMatches() method.

Maybe you just need to upgrade the API version to be able to use it in your trigger.

3
Michael Welburn On

I'm assuming that you'd change this logic to work in a Trigger.

Logically, your splitting should work, but you'll need to rearchitect it slightly to handle bulk transactions. Your best bet is probably using "before insert, before update". Then, your pseudo-code would be:

Loop over Trigger.new
  Split on \n
  Set comment_length field to size of collection

By using before, you don't actually have to explicitly make a followup save call as long as you are working on the elements in Trigger.new. This context also lets you handle a trigger with more than 1 Task.