1

I have written a trigger to update one custom field on activity which is a lookup to account.

I have to update that field with the account for account and one custom object (property relation)

When i just run a trigger for Account , it works .But when i have written the whole trigger, Its not updating the activity field for account .The trigger is working fine for Property relation object.

This is my trigger

trigger populateAccount on Task (before insert,before update) {
    List<Id> AccountIds = new List<Id>();
    String strTempId;
    if(trigger.isInsert || trigger.isUpdate){
        for(Task t : trigger.new){
            strTempId = string.valueOf(t.WhatId);
            System.debug('++++++++Test strTempId+++++++++++:'+strTempId.startsWith('001'));
            if(strTempId != null && strTempId.startsWith('001')){
                System.debug('++++++++InIF+++++++++++');
                t.Account__C = t.WhatId;
            }
            else if(strTempId.startsWith('a0p')){
                AccountIds.add(t.WhatId);
            }
        }
        map<id,id> mapAccounts  = new map<Id,id>();
        if(AccountIds.size() > 0 && AccountIds!= null){
            for(Property_Relation__c objPropertyRelation:[select id,Account__c from Property_Relation__c where id in:AccountIds]){
                mapAccounts.put(objPropertyRelation.id,objPropertyRelation.Account__c);
            }
        }

        for(Task t : trigger.new){
            t.Account__c = mapAccounts.get(t.whatId);
        }
    }
}

1 Answer 1

2

Your trigger won't update Account__c when you create the Task under an Account. Its because Account__c field is overridden to blank in this line

for(Task t : trigger.new){
    t.Account__c = mapAccounts.get(t.whatId);
}

Reason:

When you do a get from the map mapAccounts using t.whatId which is an Account Id it returns null and assigns it to Account__c because your map is populated with key as id of Property relation object and value as id of Account. So when you do a get from the map with id of Account it will always return null. So change that to

for(Task t : trigger.new){
    if(t.Account__c == NULL){
        t.Account__c = mapAccounts.get(t.whatId);
    }
}

Explanation:

The added if condition checks whether the Account__c field is null and assign the value returned from mapAccounts.

For task created on Property relation object, the Account__c will be null it will be populated here. For task created on Account, the Account__c is already populated in this line.

if(strTempId != null && strTempId.startsWith('001')){
    System.debug('++++++++InIF+++++++++++');
    t.Account__C = t.WhatId;
}

So it won't be null and the if condition gets skipped keeping the value.

Hope it helps.

You must log in to answer this question.

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