All Trigger Assignment [CRM Landing]

Trigger --> Write a trigger on opportunity to related account and find max and min amount and then populatetd on account object without aggregate fuction.

-------------------------------------------------------------------------------------------------------------------------

trigger opportunityMaxAndMin on Opportunity (after insert, after update, after delete) {

    Set<Id> accountIds = new Set<Id>();

    

    if (Trigger.isInsert || Trigger.isUpdate) {

        for (Opportunity opp : Trigger.new) {

            accountIds.add(opp.AccountId);

        }

    } else if (Trigger.isDelete) {

        for (Opportunity opp : Trigger.old) {

            accountIds.add(opp.AccountId);

        }

    }

    

    Map<Id, Account> accountsToUpdate = new Map<Id, Account>([SELECT Id, Max_Opportunity_Amount__c, Min_Opportunity_Amount__c FROM Account WHERE Id IN :accountIds]);

    

    for (Opportunity opp : [SELECT Id, AccountId, Amount FROM Opportunity WHERE AccountId IN :accountIds ORDER BY Amount]) {

        if (accountsToUpdate.containsKey(opp.AccountId)) {

            Account acc = accountsToUpdate.get(opp.AccountId);

            

            if (acc.Max_Opportunity_Amount__c == null || opp.Amount > acc.Max_Opportunity_Amount__c) {

                acc.Max_Opportunity_Amount__c = opp.Amount;

            }

            

            if (acc.Min_Opportunity_Amount__c == null || opp.Amount < acc.Min_Opportunity_Amount__c) {

                acc.Min_Opportunity_Amount__c = opp.Amount;

            }

        }

    }

    

    update accountsToUpdate.values();

}

----------------------------------------------------------------------------------------------------------------------

Q1.  Create apex trigger on contact object whenever phone number is available on contact

         update same on parent account phone field.

----------------------------------------------------------------------------------------------------------------------

trigger CountAccountContacts on Contact (before insert , before delete)

{

    Set<ID> setAccId = new Set<ID>();

    Map<Id , Integer> mapAccNewContact = new Map<Id , Integer>();

    List<Contact> conList = Trigger.IsInsert ? trigger.new : trigger.old;

    for(Contact c : conList){

        if(c.AccountId != null){

            setAccId.add(c.AccountId);

            if(mapAccNewContact.ContainsKey(c.AccountId)){

                mapAccNewContact.put(c.AccountId , mapAccNewContact.get(c.AccountId) + 1);

            }

            else{

                mapAccNewContact.put(c.AccountId , 1);

            }

        }

    }


    MAP<ID , Account> mapAcc = new Map<Id , Account>([Select id , Number_of_Contacts__c , (Select id From Contacts) from   Account where id in:setAccId]);


    for(ID accID :  mapAcc.keyset()){


        Account a = mapAcc.get(accID);


        if(Trigger.IsInsert){

            // a.Number_of_Contacts__c = a.Number_of_Contacts__c + mapAccNewContact.get(accID);

            a.Number_of_Contacts__c = a.Contacts.size() + mapAccNewContact.get(accID);

        }

        else{

            //a.CountContact__c = a.CountContact__c - mapAccNewContact.get(accID);

            a.Number_of_Contacts__c = a.Contacts.size() - mapAccNewContact.get(accID);

        }

    }        

    update mapAcc.values();

}

------------------------------------------------------------------------------------------------------------------------

Q2. Create triggers on opportunity do not allow the user to change StageName from

Qualification to close/lost.

-----------------------------------------------------------------------------------------------------------------------

List<task> tskList = new List<Task>();

    //Do not allow the user to change Stage Name from Quelification to Close Lost.

    if(Trigger.isBefore && Trigger.isUpdate){

        for(Opportunity opp : trigger.new){

            if(opp.StageName == 'Closed Lost' && Trigger.oldMap.get(opp.id).StageName=='Qualification'){

                opp.addError('Qualification cant be Closed Lost');

            }    

        }

    

//Whenever Create a record on Opportunity so should be automatacally create task

    if(Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate)){

        for(Opportunity opp : Trigger.New){

            if(opp.StageName == 'Closed Won'){

                Task tsk = New Task(); 

                tsk.whatid = opp.id;

                tsk.Subject = 'Follow Up Test Task';

                tskList.add(tsk);

            }

            if(!tskList.isEmpty()){

                //insert tskList;

            }

        }

    }

}

--------------------------------------------------------------------------------------------------------------------------

Q3. Create an apex trigger on a student object that does not allow more than 10 students in a

single class.

--------------------------------------------------------------------------------------------------------------------------

Trigger studentTrigger On Student__c(before Insert, after Update){

    Map<Id, Integer> mapOfCountRecords = new Map<Id, Integer>();

    Map<Id, Integer> mapOfCountUpdatedRecords = new Map<Id, Integer>();

    Set<Id> setOfClsIds = new Set<Id>();

    for(Student__c stu : Trigger.New){

        if(Trigger.isInsert || (Trigger.isUpdate && stu.Class__c != trigger.oldMap.get(stu.Id).Class__c)){

            setOfClsIds.add(stu.class__c);

            if(mapOfCountRecords.containsKey(stu.Class__c) ){

                mapOfCountRecords.put(stu.Class__c, mapOfCountRecords.get(stu.Class__c) + 1);

            }else{

                mapOfCountRecords.put(stu.Class__c, 1);

            }

        }

    }

    System.debug('setOfClsIds'+ setOfClsIds);

    if(setOfClsIds.size() > 0){

        List<Class__c> listOfClass = [SELECT Id, (SELECT Id, Class__c From Students__r) FROM                Class__c Where Id =: setOfClsIds];

        for(Class__c stud : listOfClass){

            Integer noOfConts;

            if(mapOfCountRecords.containsKey(stud.Id)) {

                noOfConts = stud.Students__r.size() + mapOfCountRecords.get(stud.Id) ;

                mapOfCountRecords.put(stud.id, noOfConts);

            }

        }

        for(Student__c std : Trigger.New){

            if(mapOfCountRecords.get(std.class__c) > 10){

                std.class__c.addError('Cannot created more than 10 records in a single class..!');

            }

        }

    }

}

--------------------------------------------------------------------------------------------------------------------------

Q4. On student object create following fields –

a. Fee status – Paid, Pending, Defaulter
b. Case –

Now whenever fee status is Defaulter. Create case and tag to case lookup on student object. Make
case subject -&gt; Defaulter student – Rohit Sethi(Dynamic student name).

--------------------------------------------------------------------------------------------------------------------------

trigger StudentTrigger on Student__c (before insert, before update) {

    List<Id> caseId = New List<Id>();

    List<Case> caseList = new List<Case>();

    List<Student__c> stuList = new List<Student__c>();

    if(Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)){

        for(Student__c stu : Trigger.New){

            if(stu.Fee_Status__c == 'Defaulter'){

                Case caseObj = new Case();

                caseObj.Status = 'New';

                caseObj.Origin = 'Phone';

                caseObj.Subject = stu.Name;

                caseList.add(caseObj);

                stuList.add(stu);

            }

        }

        if(!caseList.isEmpty()){

            insert caseList;

            for(Case caseObj : caseList){

                caseId.add(caseObj.id);

            }

            for(Integer i=0; i<stuList.size(); i++){

                stuList[i].case__c = caseId[i];

            }

        }

    }

}

--------------------------------------------------------------------------------------------------------------------------

Q5. On account create following fields –

a. Number of opportunities

b. Number of Contacts

c. Opp amount total

On opportunity/contact trigger to populate following fields.

--------------------------------------------------------------------------------------------------------------------------

Using Aggregate Fuction 

Map<Id, Account> mapOfAccOpp = new Map<Id, Account>();

    Set<Id> setOfAccIds = new Set<Id>();  

    if(Trigger.isAfter){ 

        if(Trigger.isInsert || Trigger.isUpdate){

            for(Opportunity opp:Trigger.new){ 

                if(Trigger.isInsert && opp.AccountId != null){

                    setOfAccIds.add(opp.AccountId);

                    System.debug('insert');

                }

                if(Trigger.isUpdate && (opp.AccountId == null && String.isNotBlank(trigger.oldMap.get(opp.Id).AccountId)) || 

                   (Trigger.isUpdate && opp.AccountId != null && opp.AccountId != Trigger.oldMap.get(opp.Id).AccountId)){

                    setOfAccIds.add(Trigger.oldMap.get(opp.Id).AccountId);

        }

            } 

        } 

        if(Trigger.isDelete ){ 

            for(Opportunity opp:Trigger.old){ 

                if(opp.AccountId != Null){

                    setOfAccIds.add(opp.AccountId);

                    System.debug('delete' + setOfAccIds);

                }   

            } 

        }

    }

    

    if(setOfAccIds.size() > 0){

        List<AggregateResult> AggregateResultList = [Select Count(Id)pls, SUM(Amount)amt, AccountId FROM Opportunity WHERE AccountId in:setOfAccIds group by AccountId]; 

        //System.debug('AggregateResultList : '+ AggregateResultList);

        if(AggregateResultList.size() > 0){ 

            for(AggregateResult aggr:AggregateResultList){

                Account acc = new Account();  

                acc.Id=(id)aggr.get('AccountId'); 

                if((Decimal)aggr.get('amt') > 0){

                    acc.Total_Amount_of_Opportunity__c = (Decimal)aggr.get('amt');

                }

                acc.Number_of_Opportunities__c = (Integer)aggr.get('pls'); 

                mapOfAccOpp.put(acc.Id, acc);

               

            }

        }else{ 

            for(Id idset1:setOfAccIds){ 

                Account acc = new Account(); 

                acc.Id = idset1; 

                acc.Total_Amount_of_Opportunity__c = 0; 

                acc.Number_of_Opportunities__c = 0;

                mapOfAccOpp.put(acc.Id, acc); 

            } 

        }   

        if(!mapOfAccOpp.isEmpty()){

            Update mapOfAccOpp.values();

        }

    }   

}

--------------------------------------------------------------------------------------------------------------------------

Without Aggregate Function 

if(Trigger.isInsert || Trigger.isUpdate){

        for(Opportunity Con : Trigger.New) {

            if((Trigger.isInsert && Con.AccountId != null) || (Trigger.isUpdate && Con.AccountId != null && Con.AccountId != Trigger.oldMap.get(Con.Id).AccountId)) {

                if(!mapOfAccOpp.containsKey(Con.AccountId)) {

                    mapOfAccOpp.put(Con.AccountId, new List<Opportunity>());

                }

                mapOfAccOpp.get(Con.AccountId).add(Con); 

                setOfAccIds.add(Con.AccountId);

                //system.debug('if condition '+ mapOfAccOpp);

            }

            if(Con.AccountId == null && String.isNotBlank(trigger.oldMap.get(Con.Id).AccountId) || (Trigger.isUpdate && Con.AccountId != null && Con.AccountId != Trigger.oldMap.get(Con.Id).AccountId)) {

                if(!mapAcctIdDelOpportunityList.containsKey(Con.AccountId)){

                    mapAcctIdDelOpportunityList.put(Trigger.oldMap.get(Con.Id).AccountId, new List<Opportunity>());

                }

                mapAcctIdDelOpportunityList.get(Trigger.oldMap.get(Con.Id).AccountId).add(Con);   

                setOfAccIds.add(Trigger.oldMap.get(Con.Id).AccountId);

                //system.debug('else condition '+ mapAcctIdDelOpportunityList);

            }

        }  

    }

    //System.debug('mapOfAccOpp : '+ mapOfAccOpp);

    

    if(trigger.isDelete) {

        for(Opportunity Con : trigger.Old) {

            if(String.isNotBlank(Con.AccountId)){

                if(!mapAcctIdDelOpportunityList.containsKey(Con.AccountId)){

                    mapAcctIdDelOpportunityList.put(Con.AccountId, new List<Opportunity>());

                }

                mapAcctIdDelOpportunityList.get(Con.AccountId).add(Con);    

                setOfAccIds.add(Con.AccountId); 

            }

        }  

    }   

    if(setOfAccIds.size() > 0) {

        listAcct = [SELECT Id, Number_of_Opportunities__c FROM Account WHERE Id IN : setOfAccIds];

        

        for(Account acct : listAcct) {

            Integer noOfConts = 0;

            if(mapOfAccOpp.containsKey(acct.Id)) {

                noOfConts += mapOfAccOpp.get(acct.Id).size();

            }

            if(mapAcctIdDelOpportunityList.containsKey(acct.Id)) {

                noOfConts -= mapAcctIdDelOpportunityList.get(acct.Id).size();

            }

            acct.Number_of_Opportunities__c = acct.Number_of_Opportunities__c == null ? noOfConts : (acct.Number_of_Opportunities__c + noOfConts);

        }

        if(!listAcct.isEmpty()){

            update listAcct;

        } 

    }

}

--------------------------------------------------------------------------------------------------------------------------

Q6. Create custom object called – Accounts Relationship Map

a. From Account - lookup

b. To Account - lookup

On Contact, create a field called parent Contact.

a. Parent Contact - Contact lookup

b. Clone Account Name on contact object - formula field - take value from Parent

contact - account - name.

On record creation of mapping objects, clone from account related contact to To Account.

Whenever the mapping record is deleted, delete the cloned records.

--------------------------------------------------------------------------------------------------------------------------

trigger AccountRelationMapTrigger on Accounts_Relationship_Map__c (after insert,after update, after delete) {

    Map<Id, Id> mapOfClone = new Map<Id, Id>();

    List<Contact> listOfClone = new List<Contact>();

    public List<Account> accountLst = new List<Account>();

    public List<Contact> fromAccountContactLst = new List<Contact>();

    List<Account> listOfAccCon = new List<Account>();

    List<Contact> conListAfterDel = New List<Contact>();  

    List<Accounts_Relationship_Map__c> listOfAccMap = new List<Accounts_Relationship_Map__c>();

    String stAutoNo ='';

    Id fromAccId;

    set<id> accIds = new set<id>();

    Map<Id,List<Contact>> mapOfDelLst = new Map<Id,List<Contact>>();

    List<Accounts_Relationship_Map__c> accRelMap = New List<Accounts_Relationship_Map__c>();

    if(Trigger.isInsert || Trigger.isUpdate){

        listOfAccMap = Trigger.new;

        System.debug('insert');

    }else if(Trigger.isDelete){

        listOfAccMap = Trigger.old;

        System.debug('delete');

    }

    for(Accounts_Relationship_Map__c arm : listOfAccMap) {

        if((Trigger.isInsert || Trigger.isUpdate)){

            mapOfClone.put(arm.From_Account__c, arm.To_Account__c);

            stAutoNo = arm.Name;

            fromAccId = arm.From_Account__c;

        }else if(Trigger.isDelete){

            stAutoNo = arm.Name;

            fromAccId = arm.From_Account__c;            

        accIds.add(arm.To_Account__c);

        }

    }

    if(Trigger.isInsert && mapOfClone != null ){

        System.debug('In Insert');

        for(Contact cObj : [select Id, FirstName, LastName, AccountId, Parent_Id__c from Contact where AccountId =: mapOfClone.keySet()]){

            Contact clone =   cObj.clone(false, true);

            clone.AccountId = mapOfClone.get(clone.AccountId);

            clone.Parent_Id__c = fromAccId;

            clone.srNo__c = fromAccId;

            listOfClone.add(clone);

        }

        if(listOfClone.size() > 0){

            Insert listOfClone;

            //System.debug(listOfClone);

        }

    }

    if(Trigger.isDelete){

        Set<Id> frmAccId = new Set<Id>();

        for(Accounts_Relationship_Map__c item : Trigger.old){

            frmAccId.add(item.From_Account__c);

        }

        for(Contact conObj : [SELECT Id, AccountId FROM Contact WHERE Parent_Id__c =: frmAccId]){

            conListAfterDel.add(conObj);

        }

        System.debug('conListAfterDel' + conListAfterDel);

        if(!conListAfterDel.isEmpty()){

            delete conListAfterDel;

        }

    }

    if(Trigger.isDelete){

        for(Contact con : [SELECT Id, Name, srNo__c FROM Contact WHERE srNo__c LIKE : stAutoNo]){

            conListAfterDel.add(con);

        }

        System.debug('Del Lst : '+ conListAfterDel);

        System.debug('SrNo : '+ stAutoNo);

        if(!conListAfterDel.isEmpty()){

            Delete conListAfterDel;

        }  

    }

}

--------------------------------------------------------------------------------------------------------------------------

Q7. Create a custom field on Product2 object called Price with decimal type. – Whenever

product2 is inserting or updating, create a price book entry with the same price.

-------------------------------------------------------------------------------------------------------------------------

trigger Product2Trigger on Product2 (after insert, after update) {

    if(Trigger.isAfter){

        Set<ID> prodIdSet = Trigger.newMap.keySet();

        if(Trigger.isInsert){

            sObject s = [select ID from Pricebook2 where IsStandard = TRUE];

            List<PricebookEntry> listOfPriBookEnt = New List<PricebookEntry>();

            for(Product2 newProduct: Trigger.new) {

                PricebookEntry priBookEntryObj = new PricebookEntry(Pricebook2Id=s.ID,Product2Id=newProduct.ID, UnitPrice=newProduct.Price__c,

                                   IsActive=TRUE, UseStandardPrice=FALSE);

                listOfPriBookEnt.add(priBookEntryObj);

            }  

            Insert listOfPriBookEnt;

        }

        if(trigger.isUpdate) {

            List<PricebookEntry> listOfUpdPBE = [SELECT Id, UnitPrice, Product2Id FROM PricebookEntry WHERE Product2ID in : prodIdSet];

            if(listOfUpdPBE != null && !listOfUpdPBE.isEmpty()) {

                Map<Id, PriceBookEntry> mapOfUpdPriBookEntry = new Map<Id, PriceBookEntry>();

                for(PricebookEntry pbe: listOfUpdPBE) {

                    mapOfUpdPriBookEntry.put(pbe.Product2Id, pbe);

                }

                for (Product2 pro : Trigger.new) {

                    

                    PriceBookEntry objPBE = mapOfUpdPriBookEntry.get(pro.Id);

                    if (objPBE != null) {

                        objPBE.UnitPrice=pro.Price__c;

                    }

                }

                Update mapOfUpdPriBookEntry.values();

            }

        }

    }

}

--------------------------------------------------------------------------------------------------------------------------

Q8. Count of related quote line item records 

--------------------------------------------------------------------------------------------------------------------------

trigger QuoteChartLineItemTrigger on Quote_Chart_Line_Item__c (after insert, after update, after delete) {

    Map<Id, List<Quote_Chart_Line_Item__c>> mapAcctIdContactList = new Map<Id, List<Quote_Chart_Line_Item__c>>();

    Map<Id, List<Quote_Chart_Line_Item__c>> mapAcctIdDelContactList = new Map<Id, List<Quote_Chart_Line_Item__c>>();

    Set<Id> AcctIds = new Set<Id>();    

    List<Quote_Chart_Summery__c> listAcct = new List<Quote_Chart_Summery__c>();

    if(Trigger.isInsert || Trigger.isUpdate){

        for(Quote_Chart_Line_Item__c Con : Trigger.New) {

            if((Trigger.isInsert && Con.Quote_Chart_Summery__c != null) || (Trigger.isUpdate && Con.Quote_Chart_Summery__c != null && Con.Quote_Chart_Summery__c != Trigger.oldMap.get(Con.Id).Quote_Chart_Summery__c)) {

                if(!mapAcctIdContactList.containsKey(Con.Quote_Chart_Summery__c)) {

                    mapAcctIdContactList.put(Con.Quote_Chart_Summery__c, new List<Quote_Chart_Line_Item__c>());

                }

                mapAcctIdContactList.get(Con.Quote_Chart_Summery__c).add(Con); 

                AcctIds.add(Con.Quote_Chart_Summery__c);

                system.debug('if condition '+ mapAcctIdContactList);

            }

            if(Con.Quote_Chart_Summery__c == null && String.isNotBlank(trigger.oldMap.get(Con.Id).Quote_Chart_Summery__c) || (Trigger.isUpdate && Con.Quote_Chart_Summery__c != null && Con.Quote_Chart_Summery__c != Trigger.oldMap.get(Con.Id).Quote_Chart_Summery__c)) {

                if(!mapAcctIdDelContactList.containsKey(Con.Quote_Chart_Summery__c)){

                    mapAcctIdDelContactList.put(Trigger.oldMap.get(Con.Id).Quote_Chart_Summery__c, new List<Quote_Chart_Line_Item__c>());

                }

                mapAcctIdDelContactList.get(Trigger.oldMap.get(Con.Id).Quote_Chart_Summery__c).add(Con);   

                AcctIds.add(Trigger.oldMap.get(Con.Id).Quote_Chart_Summery__c);

                system.debug('else condition '+ mapAcctIdDelContactList);

            }

        }  

    }

    System.debug('mapAcctIdContactList : '+ mapAcctIdContactList);

    

    if(trigger.isDelete) {

        for(Quote_Chart_Line_Item__c Con : trigger.Old) {

            if(String.isNotBlank(Con.Quote_Chart_Summery__c)){

                if(!mapAcctIdDelContactList.containsKey(Con.Quote_Chart_Summery__c)){

                    mapAcctIdDelContactList.put(Con.Quote_Chart_Summery__c, new List<Quote_Chart_Line_Item__c>());

                }

                mapAcctIdDelContactList.get(Con.Quote_Chart_Summery__c).add(Con);    

                AcctIds.add(Con.Quote_Chart_Summery__c); 

            }

        }  

    }   

    

    if(AcctIds.size() > 0) {

        listAcct = [SELECT Id, Number_of_Quote_chart_Line_item__c FROM Quote_Chart_Summery__c WHERE Id IN : AcctIds];

        

        for(Quote_Chart_Summery__c acct : listAcct) {

            Integer noOfConts = 0;

            if(mapAcctIdContactList.containsKey(acct.Id)) {

                noOfConts += mapAcctIdContactList.get(acct.Id).size();

                system.debug('plus record ');

            }

            if(mapAcctIdDelContactList.containsKey(acct.Id)) {

                noOfConts -= mapAcctIdDelContactList.get(acct.Id).size();

                system.debug('minus record ');

            }

            acct.Number_of_Quote_chart_Line_item__c = acct.Number_of_Quote_chart_Line_item__c == null ? noOfConts : (acct.Number_of_Quote_chart_Line_item__c + noOfConts);

                }

        if(!listAcct.isEmpty()){

            update listAcct;

        } 

    }

}

--------------------------------------------------------------------------------------------------------------------------

Comments

Popular posts from this blog

Custom List View Button In Salesforce

Get Record Id RecordId in LWC

PDF LWC (Link for pdf liabrary)