Search code examples
triggerssalesforceapex-codesoqlapex

Salesforce Apex: Count Number of Line Breaks in Text Field


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);

}

Solution

  • 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.