0

I have a Text Area (Long) field that was encrypted so I am unable to convert it to a Text Area (Rich) field. Therefore, I created a new Text Area (Rich) field and would like to update all Account records so that the Rich Text field = Long Text field.

Below is the code I am using. The .replaceAll('\n', '<br/>'); to preserve formatting.

List<Account> accList = [SELECT RichText__c, LongText__c FROM Account];
List<Account> accListToUpdate = new List<Account>();

for(Account a : accList)
{
    a.RichText__c = a.WM_LongText__c.replaceAll('\n', '<br/>');
    accListToUpdate.add(a);
}

update accListToUpdate;

However, I am getting the following error:

System.NullPointerException: Attempt to de-reference a null object

How can I update all of the records?

Additionally, we have over 100k records that need to be updated. Would this approach work? Or would it require something else?

1 Answer 1

1

You need to filter your accounts to only include values that are populated, and only for records that need to be updated.

The Null Pointer Exception (NPE) is generated here by replaceAll:

a.RichText__c = a.WM_LongText__c.replaceAll('\n', '<br/>');

While you can navigate across null fields (only while traversing sObject relationships):

// Safe, this is null
String ownerName = new Contact().Account.Owner.Manager.Name;

As soon as you try to call a method on a null object, you'll get a NPE:

// NPE!
String ownerName = new Contact().Account.Owner.Manager.Name.toLowerCase();

Also, you don't need to copy the accounts from one list to another. That's inefficient.

To deal with governor limits, you need to query them in batches. Just run the script over and over again until you're done.

Account[] accList = [SELECT LongText__c FROM Account WHERE LongText__c != NULL AND RichText__c LIMIT 10000];

for(Account a : accList) {
    a.RichText__c = a.LongText__c.replaceAll('\n', '<br/>');
}
Assert.areNotEqual(0, accList.size(), 'No more records to process');
update accListToUpdate;

I use an assertion at the end so that I'll intentionally get an error letting me know I can stop running the script when I'm done.

Note that in some cases, you can use the Safe Navigation Operator; I mention this only for completeness, but the appropriate solution here is to not query records without any text to begin with.

2
  • Hey @sfdcfox Thanks for your help on this. I am having some trouble with the Query part of your answer however. Getting this error: 'field 'LongText__c' can not be filtered in a query call.' Do you know if there is another way to see if these fields are Null?
    – sp2
    Feb 6, 2023 at 19:00
  • Apologies- I think I got this! I added an if statement inside the loop: if(String.isNotBlank(a.LongText__c)){add to list here}. Thank you again for your help!
    – sp2
    Feb 6, 2023 at 19:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .