Posts

Showing posts from March 26, 2017

Update Account Comment from Task Insertion Using Trigger

Requirement: Write a trigger to update account comment field from Task comment value on insertion of Task under Account Solution : trigger updateAccountCommentFromTask on Task (before insert) { String account_prefix = Schema.SObjectType.Account.getKeyPrefix(); Map<Id,Account> accountMap = new Map<Id,Account>(); Set<id> setofWhatID = new Set<id>(); for (Task objTask: Trigger.new)  { setofWhatID.add(objTask.WhatId); } Map<id,Account> MapAccIDToAccount = new Map<id,Account>([Select Id, Account_Status_Sales__c from Account Where Id in :setofWhatID]); for (Task objTask: Trigger.new) if(objTask.Subject != null && objTask.WhatId !=null && ((String)objTask.WhatId).startsWith(account_prefix)) { Account a = MapAccIDToAccount.get(objTask.WhatId); a.Comment__C = objTask.Comment__c; accountMap.put(a.id,a); } try { update accountMap.values(); } catch (system.Dmlexception e)  { system.debu

Duplicate Prevent Lead Based On Email

Requirement : Write a trigger to prevent duplicate Email on Lead Object Solution : trigger leadDuplicatePreventer on Lead (before insert, before update) { Map<String, Lead> leadMap = new Map<String, Lead>(); for (Lead lead : System.Trigger.new) { if ((lead.Email != null) &&     (System.Trigger.isInsert || (lead.Email != System.Trigger.oldMap.get(lead.Id).Email))) { if (leadMap.containsKey(lead.Email)) {   lead.Email.addError('Another new lead has the ' + 'same email address.'); } else {      leadMap.put(lead.Email, lead);  } } } for (Lead lead : [SELECT Email FROM Lead WHERE Email IN :leadMap.KeySet()]) { Lead newLead = leadMap.get(lead.Email); newLead.Email.addError('A lead with this email ' + 'address already exists.'); } }                              Thanks,                            Sumit Shukla