This method allows you to filter records based on the permissions of the current user. It can be used to remove fields and objects that the user does not have access to across a set of records. It´s often used when dealing with collections of records like a list
of SObjects where you want to filter out fields that the user does not have access to. This method could be useful to remove inaccessible fields from sObjects before DML operation to avoid exceptions.
In the provided example, you are using Security.stripInaccessible to filter out inaccessible fields, modifying a field, and then performing a DML operation to update the modified records on account object.
List<Account> accounts = [SELECT Id, Name, AccountNumber, Description FROM Account LIMIT 2];
List<Account> sanitizedAccounts = decision.getRecords();
Account firstAccount = sanitizedAccounts[0]; firstAccount.Name = ‘New Updated Name’;
}
if (!sanitizedAccounts.isEmpty()) {
update sanitizedAccounts;
}
// Retrieve the updated account records
List<Account> updatedAccounts = [SELECT Id, Name, AccountNumber, Description FROM Account WHERE Id IN :sanitizedAccounts];
This code retrieves a list of accounts from the database and then uses the Security. stripInaccessible() method to remove any inaccessible records based on the READABLE access type.
The sanitized account records are stored in the sanitizedAccounts list. The code then modifies the Name field of the first account in the sanitizedAccounts list, setting it to “New Updated Name”. Next, a DML update operation is performed on the sanitizedAccounts list to persist the changes to the database.
The code then queries the updated account records from the database, including the Id, Name, AccountNumber, and Description fields for the updated accounts. Finally, a debug statement is used to display the updated account records in the debug logs.
The use of Security.stripInaccessible() is important as it ensures that only accessible records are included in the sanitizedAccounts list. This helps maintain data security by filtering out any inaccessible records before performing the update operation. By using this method, the code respects the user’s access privileges and ensures that updates are only made to records that the user has the necessary permissions to modify.