Wednesday, November 12, 2014

Salesforce + Finding out "How deleted out the records"

If you need to find out who is deleting your records, you can write this code on the Execute Anonymous block (either on the force.com IDE or the Force.com Console):

for (List<Account> Accs : [SELECT Id, LastModifiedByID, LastModifiedBy.userName, LastModifiedBy.name, LastModifiedDate, Name
                           FROM Account
                           WHERE IsDeleted = true
                           ALL ROWS]) {
    for (Account acc : Accs) {
        String str = '';
        str += 'Account [' + Acc.Name + '] ';
        str += 'was deleted by [' + acc.LastModifiedBy.name + ' ';
        str += '(' + acc.LastModifiedBy.userName + ')] ';
        str += 'on [' + acc.LastModifiedDate + ']';
        System.debug(str);
    }
}

You could also perform a similar operation using Data Loader (v20 or later) by clicking on the [Export All] button and using this query:

SELECT Id, LastModifiedByID, LastModifiedBy.userName, LastModifiedBy.name, LastModifiedDate, Name
FROM Account
WHERE IsDeleted = true

This works in Data Loader because it uses the QueryAll() method when connecting to Salesforce using the Webservices API.

Trigger + Write Once Data for Field + Salesforce

This trigger will prevent records from being deleted or fields from being changed once they have been set, so they are write-once. Note, the other fields can be written many times but the specific field's value can only be set when the record is created.

trigger Trigger_Account on Account (before delete, before update) {

    if (trigger.isDelete) {
        for (Account a : trigger.old) {
            a.addError('You can’t delete accounts');
        }
    } else {
        for (Account aNew : trigger.new) {
            Account aOld = Trigger.oldMap.get(aNew.ID);
            if (aNew.Phone != aOld.Phone) {
                aNew.Phone = aOld.Phone;
            }
        }
    }
}