while creating child record need to get data from Grand parent. i wrote a trigger but not updating fields. here my working.   trigger Registration on Opportunity (after Update) {      list&lt;Registration__c&gt; NewReg = new list&lt;Registration__c&gt;();     list&lt;Registration__c&gt; oldReg = new list&lt;Registration__c&gt;();      for(opportunity o : Trigger.new){         if(o.Registration_Raised__c==true) {             oldReg = [select id,Name from Registration__c where Opportunity__c=:o.id];             if(oldReg.size()==0){                 registration__C reg = new registration__c();                 reg.Opportunity__c = o.id;                 reg.GHMC_Approved_Date__c = O.Unit_Number__r.Tower__r.GHMC_Approved_Date__C;                 NewReg.add(reg);             }         }            }     if(NewReg.size()&gt;0){         insert NewReg;     }  }   i wrote the above trigger on opportunity and registration__C is the child object. when registraion raised check box is true the child record will create and need some inform Gran parent object. those are, Unit__C and tower__C.
51103
I am populating a junction object on from Events and want to capture info from the Event but getting the Account from Account field pulls null. Same who the name via the Who. But if I query the Event record, the AccountId field is populated. And of course, the code compiles properly. Can someone explain how to grab this related info?  trigger TripMeetingFromMeeting on Event (after insert, after update) {      Set&lt;id&gt;EventId = new Set &lt;ID&gt;();     List &lt;Trip_Meeting__c&gt; TMS = new List &lt;trip_meeting__c&gt;();      for (Event E:trigger.new){         if (e.Business_Trip__c!=null){             TMS.add(new Trip_Meeting__c(Meeting__c =e.id, Business_trip__c=e.Business_Trip__c,                                         Meeting_Date__c=e.ActivityDate, Meeting_subject__c=e.Subject,                                        TripNameDELETE__c=e.Business_Trip__r.name,                                         mWhatID__c=e.Whatid,                                        Meeting_Company__c=e.Account.name,                                        Meeting_Name__c=e.Who.name)                                         );          }     }     system.debug('TMS!!!============================'+TMS);      Database.insert(tms, false);  }
64326
Can any one out here give me a scenario for recursive trigger. Why don't we able to control the trigger in the same place. Why do we go for a class under every trigger Context. Please provide me a scenario where recursive trigger occur.
27810
trigger preventAccountDeletionifopp on Account (before delete) {     for(account accdel:trigger.old){        Opportunity oppprevent =[select Name,(select Name,Owner from Opportunitys)from ACCOUNT =: accdel.id ];         if(oppprevent.size() &gt; 0){           accdel.adderror('Opportunity record is refering this record.So, you cannot delete it...!');         }    } }
85058
I am not able to sum all the opportunities under the account ?  How will I do that?  What I have to use in this to run the trigger? Is it possible to create because opp. is child and account is parent ?  trigger sumAllopptyAmtAccount on Account(before insert) {     Set &lt; ID &gt; AccID = New Set &lt; ID &gt; ();     if (Trigger.isInsert)         for (Account oppAc: trigger.New) {             AccID.add(oppAc.AccountID);         }     List &lt; Account &gt; acc = [select id, SumAll_Opprty__c from Account where id in: a.AccID];     List &lt; Opportunity &gt; opp = [selece id from Opportunity where AccountID in: a.AccID];     for (Account a: acc) {         a.SumAll_Opprty__c = con.size();     } }
60488
I am opening this question after reading this:   I have this query [SELECT id, DISTANCE(some_field__c, GEOLOCATION(0,0), 'mi') distance FROM Parent__c LIMIT 1] and that's working fine.   However when I try to execute this query starting from the child:  [SELECT id, DISTANCE(Parent__r.some_field__c, GEOLOCATION(0,0), 'mi') distance FROM Child__c LIMIT 1] I get an error saying No such column 'distance' on entity Child__c. Is this a salesforce limitation or am I doing something wrong?
93357
My Trigger will send an email anytime one account has 7 cases created within 8 days. Towards the bottom in my Else block, I am trying to access fields in my first SOQL statement. I have tried many ways and read many help pages. Help with the syntax for the line: message.PlainTextBody = 'Account name: ' + cl.get('name') + ' has ' + (Integer)cl.get('co') + ' cases opened in the last 8 days.';`  is greatly appreciated.  List&lt;AggregateResult&gt; AggregateResultList = [SELECT AccountId, Account.Name name, COUNT(Id) co                                          FROM Case                                          WHERE CreatedDate = LAST_N_DAYS:8                                          GROUP BY AccountId, Account.Name                                          HAVING COUNT(Id)  &gt;= 7];                           Set&lt;Id&gt; AcctIds = new Set&lt;Id&gt;();                 for(AggregateResult aggr: AggregateResultList){                      Id accId = (Id)aggr.get('AccountId');                         AcctIds.add(accId);                 }                  List&lt;Case&gt; caseList = [SELECT Id, AccountId, Account.Name,Parent_Project_if_applicable__r.Implementation_status__c,                                                 Parent_Project_if_applicable__r.PM_Implementation_Status__c,                                                  Parent_Project_if_applicable__r.RCM_Implementation_Status__c                                            FROM Case                                        WHERE AccountId IN :AcctIds];             Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();             for(Case cl:caseList){                   if(cl.Parent_Project_if_applicable__r.Implementation_status__c == 'Live - Closed Project'){                             //Private method *** getAddresses() *** retrieves email address from Customer_Success_Managers Public Group                              message.toAddresses  = getAddresses();                            }                         else{                                message.toAddresses = new String[] { Parent_Project_if_applicable__r.Client_Advisor_Email__c  };                          }                     message.Subject = 'Subject Test Message';                     message.PlainTextBody = 'Account name: ' + cl.get('name') + ' has ' + (Integer)cl.get('co') + ' cases opened in the last 8 days.';                     Messaging.SingleEmailMessage[] messages =   new List&lt;Messaging.SingleEmailMessage&gt; {message};                     Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);             } private List&lt;String&gt; getAddresses(){ List&lt;User&gt; UserList =         [SELECT id, name, email         FROM User          WHERE id          IN (SELECT userorgroupid              FROM groupmember             WHERE group.name = 'Customer Success Managers')];  List&lt;String&gt; emailString = new List&lt;String&gt;();  for(User u: UserList){     emailstring.add(u.email); }    return (emailString); }
121895
I have a trigger and a class that seem to be causing an insert fail in Dataloader.  I am trying to insert 200 records to see if an error is generated before moving these to production. I'm just inserting the mandatory fields such as Name, Owner, Market, Customer_Success_Manager__c, and Business Unit.   Each time I get an error:     UpdateCSMTeam:execution of AfterInsertcaused by: System.DmlException:   Insert failed. First exception on row 0 with id01MJ0000009gXthMAE;   first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an   insert call: [Id]Class.UpdateCSM.updateTeamMem . I've listed the class   and trigger below.   APEX CLASS  public class UpdateCSM {             public static void updateTeamMember(List&lt;Account&gt; accounts) {                     List&lt;AccountShare&gt; ashareLIST = new List&lt;AccountShare&gt;();                     List&lt;AccountTeamMember&gt; ATM = new List&lt;AccountTeamMember&gt;();                    Set&lt;String&gt; rmMember = new Set&lt;String&gt;();                     Map&lt;ID, ID&gt; acctToBRepMap = new Map&lt;ID, ID&gt;();                      for(Account a:accounts){                              AccountShare caSharingRule = new AccountShare();                                caSharingRule.AccountId = a.Id;                                caSharingRule.OpportunityAccessLevel = 'Edit';                                caSharingRule.CaseAccessLevel = 'Edit';                                caSharingRule.AccountAccessLevel = 'Edit';                                caSharingRule.UserOrGroupId = a.Customer_Success_Manager__c;                                ashareLIST.add(caSharingRule);                                    if(a.Customer_Success_Manager__c!= null){                                   AccountTeamMember Teammemberad=new AccountTeamMember();                 Teammemberad.AccountId=a.id;                 Teammemberad.UserId=a.Customer_Success_Manager__c;                 Teammemberad.TeamMemberRole = 'Customer Success Manager';                                   ATM.add(Teammemberad);                             if(!ATM.isEmpty()){                                    insert ATM;                                              insert ashareLIST;                                                         if(a.Customer_Success_Manager__c==null){                                            list&lt;AccountTeamMember&gt; ratm = [SELECT UserId                                                                             FROM AccountTeamMember                                                                             WHERE (TeamMemberRole = 'Customer Success Manager')                                                          AND AccountId =:a.id];                                             if(ratm.size()&gt;0)                                                 delete ratm;                                        }                                    }                                 }                            }                         }                    } ...   APEX TRIGGER  trigger UpdateCSMTeam on Account (After update, After insert){         UpdateCSM.updateTeamMember(trigger.new); }
16527
A general question asked from time to time on stack exchange is question of trigger bulkification.  Therefore I have 2 questions:   Which best practices are you using? What is the best way to handle updates of more than 200 records? (In case of more than 200 records the trigger is executed more than once.)
27742
I have process in salesforce in such a way opportunity we can relate this opportunity to this lookup field parent_opportunity__c . Which relates opportunity to other parent opportunity.  I want to write a query parent to child :  select id,(select id from opportunity where parent_opportunity__c!=null) from opportunity where parent_opportunity__c=null   I have worked with different scenarios i cant able to crack it  select id,name,(select id,name from parent_opportunity__r) from opportunity this is showing error and   select id,name,(select id,name from opportunity) from parent_opportunity__c this is also error
118936
I am trying to follow the best practice design patterns for triggers but get the error Constructor not defined: [CaseTriggerHandler].(). What am I missing?  Trigger  trigger CaseTrigger on Case (before insert, before update, before delete, after insert, after update, after delete, after undelete) {      CaseTriggerHandler handler = new CaseTriggerHandler();      //Before Insert     if(Trigger.isInsert &amp;&amp; Trigger.isBefore){         handler.OnBeforeInsert(Trigger.new);     }     //After Insert     else if(Trigger.isInsert &amp;&amp; Trigger.isAfter){         handler.OnAfterInsert(Trigger.new);     }     //Before Update     else if(Trigger.isUpdate &amp;&amp; Trigger.isBefore){         handler.OnBeforeUpdate(Trigger.old, Trigger.new, Trigger.newMap);     }     //After Update     else if(Trigger.isUpdate &amp;&amp; Trigger.isAfter){         handler.OnAfterUpdate(Trigger.old, Trigger.new, Trigger.newMap);     }     //Before Delete     else if(Trigger.isDelete &amp;&amp; Trigger.isBefore){         handler.OnBeforeDelete(Trigger.old, Trigger.oldMap);     }     //After Delete     else if(Trigger.isDelete &amp;&amp; Trigger.isAfter){         handler.OnAfterDelete(Trigger.old, Trigger.oldMap);     }     //After Undelete     else if(Trigger.isUnDelete){         handler.OnUndelete(Trigger.new);     } }   Handler      public with sharing class CaseTriggerHandler {      private boolean isExecuting = false;      public CaseTriggerHandler(boolean isExecuting){         this.isExecuting = isExecuting;     }      public void OnBeforeInsert(List&lt;Case&gt; newCases){         //EXECUTE BEFORE INSERT LOGIC     }      public void OnAfterInsert(List&lt;Case&gt; newCases){         //EXECUTE AFTER INSERT LOGIC     }      public void OnBeforeUpdate(List&lt;Case&gt; oldCases, List&lt;Case&gt; updatedCases, Map&lt;Id, Case&gt; CaseMap){         //BEFORE UPDATE LOGIC     }      public void OnAfterUpdate(List&lt;Case&gt; oldCases, List&lt;Case&gt; updatedCases, Map&lt;Id, Case&gt; CaseMap){         //AFTER UPDATE LOGIC     }      public void OnBeforeDelete(List&lt;Case&gt; CasesToDelete, Map&lt;Id, Case&gt; CaseMap){         //BEFORE DELETE LOGIC     }      public void OnAfterDelete(List&lt;Case&gt; deletedCases, Map&lt;Id, Case&gt; CaseMap){         //AFTER DELETE LOGIC     }      public void OnUndelete(List&lt;Case&gt; restoredCases){         //AFTER UNDELETE LOGIC     }      public boolean IsTriggerContext{         get{ return isExecuting;}     } }
96175
Well while doing some research found that Rollup fields are not updated in after trigger(am querying the field again using an SOQL from the trigger). This seems to be unexpected as per my knowledge they should be updated in after trigger.  Is it something expected or am doing something wrong?
40980
The trigger creates a related record when a checkbox is updated. The problem is it is creating a new related record everytime the record is edited. I want to edit the trigger to only create the related record once. (When the criteria is first met). The code is below  Trigger copyEquipmentonsite on Unit_Placements_Sales__c(after insert, after update) {      List&lt;Services__c&gt; sub=new List&lt;Services__c&gt;();      for(Unit_Placements_Sales__c u : Trigger.new) {           if(u.Service_Month_is_Next_Month__c == TRUE) {                 Services__c s = new Services__c();                 s.Equipment_Onsite__c=u.ID;                 s.Equipment_Type__c=u.Equipment__c;                 s.Machine_Specific_Notes__c=u.Machine_Specific_Notes__c;                    s.Product__c=u.The_Product__c;                   s.Dell_Tag_Number__c=u.Dell_Tag_Number__c;                 s.Serial_Number__c=u.Serial_Number__c;                  s.XD_Number__c=u.XD_Number__c;                 sub.add(s);           }           if(sub.size()&gt;0)           insert sub;      } }
20008
I have a custom object that has a master-detail relationship with another object, which has a master-detail relationship with another object. To simplify, consider them as: order, order item and receipt note.  Every time an item arrives, a "receipt" record is created, which specifies the amount of items that arrived. So if an order has 10 units of 1 item, it is possible to receive 10 or less at once.  On the order item I have a field called "received amount" which sums the "quantity" field from related receipts. So I know, for example, when X out of Y items arrived. I have a similar relationship with the item and the parent, that shows how many items were totally delivered.   The problem is that on the grand-children record (receipt) I have a trigger running on after insert which is supposed to check on the parent (order) if all the items were received (AmountOfItems == DeliveredItems), but the parent record, when queried on the trigger, doesn't display the updated value on the DeliveredItems roll-up field when the trigger code is running.  After the trigger runs, right before my test method exists, I query the parent again to check the fields, and I can see the value updated.  My guess is that this is either a bug, or the fields are calculated only after all the trigger context is run by the platform (which includes the after insert event). Am I right? How can I get around this?
96142
I am working on a requirement to create an opportunity and opportunity products , when there is an update on the asset object.  The asset object has a filed called Refresh_Asset_To__c, this is a lookup to the product object.   Basically each time I change the product on the Refresh_Asset_To__c, a new opportunity should be generated with the Refresh_Asset_To__c being the opportunity product.  I have tested , and its generating the opportunity , but each time i try to insert the opportunity product I get the error :      Update failed. First exception on row 0 with id 02i3B000003TAk7QAG; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AssetRefreshOpp: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: PricebookEntryId (pricebook entry currency code does not match opportunity currency code): [PricebookEntryId] Trigger.AssetRefreshOpp: line 56, column 1: []   This is my code:  trigger AssetRefreshOpp on Asset (after update) {      Pricebook2 ikmBook    = [SELECT Id,CurrencyIsoCode FROM Pricebook2 WHERE Id = '01s46000003K1zXAAS'];  List&lt;OpportunityLineItem&gt; oppLiList = new List&lt;OpportunityLineItem&gt;(); Opportunity opp; OpportunityLineItem oli; string refeshed;     List&lt;asset&gt; refreshedAss = [select Id,Contract__r.EndDate,OwnerId,quantity,Name,Refresh_Asset_To__c,Refresh_Asset_To__r.Id,AccountId,account.name from asset                                      where Id IN : Trigger.new                                      And Refresh_Asset__c = True];          for(asset myAss:refreshedAss){             // Create New Opportunity              Opportunity newopp =new Opportunity();   newopp.Name=myAss.account.name + ' ' + 'refreshed'; newOpp.AccountId = myAss.AccountId; newOpp.CloseDate = myAss.Contract__r.EndDate; newOpp.StageName = 'Create'; newOpp.RecordTypeID = '01246000000TfMZAA0'; newOpp.OwnerId = myAss.OwnerId; newOpp.Amount = 0; newOpp.Type= 'Existing Business'; newOpp.OM_Order_Type__c = 'Regular'; newOpp.CurrencyIsoCode = ikmBook.CurrencyIsoCode; newOpp.Pricebook2Id = ikmBook.Id;  insert newOpp;          List&lt;PriceBookEntry&gt; priceBookList = [SELECT Id, Product2Id,CurrencyIsoCode, Product2.Id, Product2.Name FROM PriceBookEntry WHERE  PriceBook2.isStandard=true LIMIT 1];               for(asset myAssets:refreshedAss){               OpportunityLineItem oli = new OpportunityLineItem();                oli.OpportunityId = newOpp.Id;                oli.Product2Id = myAssets.Refresh_Asset_To__r.Id;                oli.PriceBookEntryId = priceBookList[0].Id;                oli.UnitPrice = 0;               oli.Quantity = myAssets.Quantity;               oppLiList.add(oli);           }           insert oppLiList;               } }
66376
I have written a trigger on custom object Order_Item__c. This object has a custom field Shipping_Number__c. When the user enters value in Shipping_Number__c and clicks save, the contact lookup field will automatically populate with contact record which has same shipping number as the value entered by the user. The trigger is working fine. I am unable to get code coverage. The coverage is 0%. Any insights will be lot helpful.  Trigger:  trigger updatelookupfield on Order_Item__c (before update, before insert)  {       Set&lt;String&gt; shippingNumbers = new Set&lt;String&gt;();      for (Order_Item__c collectNumFromOrder : Trigger.new) {         shippingNumbers.add(collectNumFromOrder.Shipping_Customer_Number__c);     }        List&lt;Contact&gt; contactList = [SELECT id, Shipping_customer_number__c FROM Contact WHERE Shipping_Customer_Number__c IN :shippingNumbers];      Map&lt;String, Contact&gt; shippingNumToContactMap = new Map&lt;String, Contact&gt;();      for (Contact c : contactList) {         shippingNumToContactMap.put(c.Shipping_customer_number__c, c);     }      for (Order_Item__c o : Trigger.new) {            if (o.Shipping_Customer_Number__c != null) {             o.RSM_Shipping_Contact__c = shippingNumToContactMap.get(o.Shipping_Customer_Number__c).id;         }         else {             o.RSM_Shipping_Contact__c = null;         }      }     }    Test Class:  @isTest public class testupdatelookupfield{      Static testMethod void insertOrderItem()     {   // create and insert the contact record - this part is correct         contact c = new contact();         c.Shipping_Customer_Number__c = '0987654';         c.lastName = 'Surekha';        insert c;           // create an order item and insert it         Order_Item__c op = new Order_Item__c();          op.Name = 'Test Varun Order';         op.Shipping_Customer_Number__c = '0987654';         insert op;           system.assertequals(op.RSM_Shipping_Contact__c,c.id);     } }
33511
I was trying to accomplish this through a trigger, but its not really working. Is there a way to get this done through Process Builder? If so, what is that process?  I'm trying to have ProductB being added to the opportunity automatically once ProductA is manually added to the opportunity.  Also, is there a way to have the $ amount of ProductB being 0.5% of ProductA?  Trigger that I have so far:  trigger Attempt1 on OpportunityLineItem (after insert) { List&lt;OpportunityLineItem&gt; oliList = new List&lt;OpportunityLineItem&gt;();  for( OpportunityLineItem item: [SELECT  OpportunityId,                                          Name                                  FROM    OpportunityLineItem                                 WHERE   Id = :Trigger.new AND                                          Name = 'NAME OF PRODUCTA'])  {   oliList.add(new OpportunityLineItem(     OpportunityId = item.OpportunityId,      PricebookEntryId ='01uA000000QPDldEAt',     Quantity = 1,     UnitPrice = 25)   );  }  Insert oliList; }
106099
I'm working on developing a test class for my apex. I'm stuck with creation of Contract records contractnumber field. In test class, I use the following code:     Contract c = new Contract();     c.Name = 'Test Contract';     c.AccountId = acc.Id;     c.Status = 'Draft';     insert c;     //I'm creating a draft contract and then activating it.     c.status  = 'Activated';     update c;     system.debug('contract debug:'+c.contractnumber);  Contractnumber field on object is Autonumber, but in the log I get null for contractnumber. I see the whole contract record is created with null ContractNumber. What am I doing wrong?