I need help to create a test class for my trigger below: trigger UpdateLeadLastMQLDate on Event (before update) {   Map&lt;Id, Lead&gt; leads = new Map&lt;Id, Lead&gt;();      for(Event record: Trigger.new) {         if(record.WhoId?.getSObjectType() == Lead.sObjectType) {             leads.put(record.WhoId, null);         }     }     leads.putAll([SELECT Last_MQL_Date_Time__c FROM Lead WHERE Id = :leads.keySet()]);     for(Event record: Trigger.new) {         record.Lead_Last_MQL_Date_Time__c= leads.get(record.WhoId)?.Last_MQL_Date_Time__c;     } }  Here the test class: @isTest (seeAllData=false) private class TestUpdateLeadLastMQLDate {     static testMethod void testEventTrigger() {         // set up leads         List&lt;Lead&gt; testLeads = new List&lt;Lead&gt;();         Lead lead1 = new Lead();         lead1.Company = 'Test 1 New Company';         lead1.LastName = 'Brian';         lead1.LeadSource = 'Website';         lead1.Status = 'MQL';         lead1.Email = 'test@test.com';         lead1.Country = 'USA';         lead1.Last_MQL_Date_Time__c = DateTime.parse('17/06/2020 13:00');         //lead1.Business_Type__c = 'App/Business';         //lead1.Lead_Role__c = 'Product';         testLeads.add(lead1);                  Lead lead2 = new Lead();         lead2.Company = 'Test 12';         lead2.LastName = 'Jordan';         lead2.LeadSource = 'Personal';         lead2.Status = 'New';         lead2.Email = 'test23@test.com';         lead2.Country = 'France';         lead2.Last_MQL_Date_Time__c = DateTime.parse('17/06/2020 13:00');         //lead2.Business_Type__c = 'App/Business';         //lead2.Lead_Role__c = 'Product';         testLeads.add(lead2);         insert testLeads;                  // set up Events         List&lt;Event&gt; events = new List&lt;Event&gt;();         Event event1 = new Event();         event1.WhoId=testLeads[0].Id;          event1.Subject= 'Test0';         event1.Type='New';         event1.STARTDATETIME=System.today();         event1.ENDDATETIME=System.today();         event1.Sales_Rep__c = '0052o000009lZyVAAU';         event1.Description = 'bla';         events.add(event1);                           Event event2 = new Event();         event2.WhoId=testLeads[1].Id;          event2.Subject= 'Test1';         event2.Type='Other';         event2.STARTDATETIME=System.today();         event2.ENDDATETIME=System.today();         event2.Sales_Rep__c = '0052o000009lZyVAAU';         event2.Description = 'bla';         events.add(event2);              Test.startTest();         insert events;         Test.stopTest();                  /*List&lt;Lead&gt; leadResults = [SELECT Last_MQL_Date_Time__c FROM Lead WHERE Id IN :testLeads];*/         List&lt;Event&gt; eventResults = [SELECT Lead_Last_MQL_Date_Time__c FROM Event WHERE Id IN :events];         for (Event e : eventResults) {             //System.assertEquals(true, l.SQL_Scheduled__c);             System.assertEquals(e.Lead_Last_MQL_Date_Time__c, DateTime.parse('17/06/2020 13:00'));         }     } }
15426
How do I write a unit-test / test class for a trigger?  What are my options?   Inline with the trigger?  New Class?
112233
To communicate with a REST interface on a private system, I need to send a JSON message from a trigger. I have a message object that has some fields, lists and a child object:  public class MerchantConfig {  public class MIDConfig {     public String mid;     public String currencyCode;     public String cardTemplateName;     public String paymentPanelRestriction;     public List&lt;String&gt; restrictedCountries;      public String paymentPanelRestrictionForCountries; }  public String merchantName; public String sopgTemplateName; public Integer dispositionTimeWindowInMinutes; public List&lt;String&gt; features; public Boolean activateImmediately; public List&lt;MIDConfig&gt; midConfiguration; }   I can serialize it to JSON using the built-in serializer:  String body = JSON.serializePretty([MerchantConfig instance]);   The result:  {   "sopgTemplateName" : null,   "midConfiguration" : [ {     "restrictionCountries" : [ "DE", "AT" ],     "paymentPanelRestrictionForCountries" : "MANDATORY",     "paymentPanelRestriction" : "OPTIONAL",     "mid" : "1000000001",     "currencyCode" : "EUR",     "cardTemplateName" : null   }, {     "restrictionCountries" : [ ],     "paymentPanelRestrictionForCountries" : "",     "paymentPanelRestriction" : "OPTIONAL",     "mid" : "1000000002",     "currencyCode" : "USD",     "cardTemplateName" : null   }, {     "restrictionCountries" : [ ],     "paymentPanelRestrictionForCountries" : "",     "paymentPanelRestriction" : "PROHIBITED",     "mid" : "1000000003",     "currencyCode" : "AUD",     "cardTemplateName" : null   } ],   "merchantName" : "Test Merchant",   "features" : [ XYZ ],   "dispositionTimeWindowInMinutes" : 10,   "activateImmediately" : true }   How can I serialize this object so that all properties that are null don't show up in the JSON string?   In this example, "sopgTemplateName" and all "cardTemplateName" properties are null and should not appear in the JSON string. The empty list "restrictionCountries" should still appear as an empty list, though.
44160
I have a Batch class that sends an Email from its finish method and want to test that. a But....I cannot test it. The the above test fails as there was no email invocation at all. BUT: I see it in the Limits view of my Dev Console that indeed one email invocation happens. Why?!  The batch class:  public MyBatch implements Database.Batchable&lt;SObject&gt; {      ...      public void finish(Database.BatchableContext context) {         sendEmail();     } }   The test method:  @isTest private static void sendsEmailOnFinish() {      Test.startTest();        MyBatch b = new MyBatch();     Database.executeBatch(b);     Test.stopTest();       // Verify     System.assertEquals(1, Limits.getEmailInvocations()); }   I thought this might be connected to using Test.startTest() and stopTest() but even moving the assertEquals before the Test.stopTest() doesn't make my test run.
57036
When I used to create the record in Event object it is showing error like:     Error: Invalid Data.   Apex trigger General_Event_Trigger caused an unexpected exception, contact your administrator: General_Event_Trigger: execution of BeforeINsert caused by: System.NullPointerException: Attempt to de-reference a null object: Class.EventClass.updateNewCustomFieldsEvent: line 369, column 1   Trigger code:  trigger General_Event_Trigger on Event (...) {     if (trigger.isBefore)     {         if (trigger.isInsert)         {             EventClass.updateNewCustomFieldsEvent(trigger.new);         }         else if (trigger.isUpdate)         {             EventClass.updateNewCustomFieldsEvent(trigger.new);         }     } }   Apex class:  public static void updateNewCustomFieldsEvent(List&lt;Event&gt; eventList) {     for (Event eve : eventList)     {         if (Administrators__c.getInstance().Update_field_Last_Modified_End_User__c)         {             String userIdString = eve.LastModifiedById;             eve.Last_Modified_By_End_User__c = userIdString.subString(0, 15);             eve.Last_Modified_Date_End_User__c = eve.LastModifiedDate;         }     } }
15516
I have some code that raises PropertyChanged events and I would like to be able to unit test that the events are being raised correctly.  The code that is raising the events is like  public class MyClass : INotifyPropertyChanged {    public event PropertyChangedEventHandler PropertyChanged;       protected void NotifyPropertyChanged(String info)    {         if (PropertyChanged != null)         {             PropertyChanged(this, new PropertyChangedEventArgs(info));         }    }       public string MyProperty    {        set        {            if (_myProperty != value)            {                _myProperty = value;                NotifyPropertyChanged("MyProperty");            }        }    } }   I get a nice green test from the following code in my unit tests, that uses delegates:  [TestMethod] public void Test_ThatMyEventIsRaised() {     string actual = null;     MyClass myClass = new MyClass();      myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)     {          actual = e.PropertyName;     };      myClass.MyProperty = "testing";     Assert.IsNotNull(actual);     Assert.AreEqual("MyProperty", actual); }   However, if I then try and chain the setting of properties together like so:  public string MyProperty {     set     {         if (_myProperty != value)         {             _myProperty = value;             NotifyPropertyChanged("MyProperty");             MyOtherProperty = "SomeValue";         }     } }  public string MyOtherProperty {     set     {         if (_myOtherProperty != value)         {             _myOtherProperty = value;             NotifyPropertyChanged("MyOtherProperty");         }     } }   My test for the event fails - the event that it captures is the event for the MyOtherProperty.  I'm pretty sure the event fires, my UI reacts like it does, but my delegate only captures the last event to fire.  So I'm wondering: 1. Is my method of testing events correct? 2. Is my method of raising chained events correct?
113469
The objective is to have assignment rules fired on a Lead record creation. It seems the rule can be assigned only when using "update" DML in an "after insert" trigger. Why does another DML must be executed after insert to have lead assignment rule assigned?   //Does not work trigger LeadTrigger on Lead (before insert) {         for (Lead l : Trigger.new) {                 Database.DMLOptions dmo = new Database.DMLOptions();         dmo.assignmentRuleHeader.useDefaultRule = true;         so.setOptions(dmo);     } }   //Works: Records must be *updated* in after insert trigger in order to have the rule assigned trigger LeadTrigger on Lead (after insert) {     List&lt;Lead&gt; ls = new List&lt;Lead&gt;();      for (Lead l : Trigger.new) {         ls.add(new Lead(id = l.id));     }      Database.DMLOptions dmo = new Database.DMLOptions();     dmo.assignmentRuleHeader.useDefaultRule = true;     Database.update(ls, dmo); }   Moreover, testing of the rule assignment fails even though the rule has been assigned to the Lead. We cannot test assignment rule outcome (ownerId=defaultQueueId for example) since the rule will change on PROD eventually.  //Test method failing for a lead *having* rule assigned:     public static void assertDefaultAssignmentRules(SObject sobj) {     Database.DMLOptions dmo = sobj.getOptions();      System.assertNotEquals(null, dmo, 'DMLOption is null');     System.assert(dmo.assignmentRuleHeader.useDefaultRule, dmo); }
34471
What is wrong in the below trigger syntax, I am getting this error An unexpected token "INT" was found following " DECLARE NULL_ROW_ID".  Expected tokens may include:  "END-OF-STATEMENT".. SQLCODE=-104, SQLSTATE=42601, DRIVER=3.68.61  CREATE TABLE A (     A_ID INT NOT NUll,     A_CODE VARCHAR(100) NOT NULL,     PRIMARY KEY(A_ID) );  CREATE TABLE B (     B_ID INT NOT NUll,     B_CODE VARCHAR(100) NOT NULL,     A_ID INT,     PRIMARY KEY (B_ID),     FOREIGN KEY (A_ID) REFERENCES A (A_ID)  );  CREATE OR REPLACE TRIGGER B_TRIGGER AFTER UPDATE OF A_ID ON B REFERENCING NEW AS N OLD AS O FOR EACH ROW     WHEN (N.A_ID IS NULL)     BEGIN ATOMIC         DECLARE NULL_ROW_ID INT;         SET NULL_ROW_ID = (SELECT A_ID FROM A WHERE A_CODE = 'Custom Null String');         IF NULL_ROW_ID IS NULL THEN             SIGNAL SQLSTATE '70000' SET MESSAGE_TEXT = 'Custom Null String row not found.';         END IF;     SET N.A_ID = NULL_ROW_ID;     END @   It's on DB2 Express-C 10.5
70777
I have an afterInsert trigger on Events. When the Script is finished, I would like to delete the event. I keep getting this error message.     DML statement cannot operate on Trigger.new or Trigger.old   If I cannot do this within Trigger.new, what is the best way to do this? If SOQL is involved, what field am I looking for? event.ID?
45672
This question has been asked before, but none of the answers on those threads have helped so far.  Getting the following error when trying to deploy a test class from the sandbox to production in the Force.com IDE:  System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, LeadPerson: execution of AfterInsert caused by: System.Exception: Too many SOQL queries: 101  LeadPerson trigger looks OK, e.g., no SOQL calls inside a loop.  trigger LeadPerson on Lead (after insert) {     Map&lt;Id, Lead&gt; leadMap = new Map&lt;Id, Lead&gt;();     Map&lt;String, Lead&gt; leadEmailMap = new Map&lt;String, Lead&gt;();      for(Lead lead : Trigger.new) {         if (lead.Email != null) {             leadMap.put(lead.Id, lead);             leadEmailMap.put(lead.Email, lead);         }     }      Map&lt;String, Person__c&gt; personMap = new Map&lt;String, Person__c&gt;();     for (Person__c p : [SELECT Id, Email__c FROM Person__c WHERE Email__c IN :leadEmailMap.keySet()]) {         personMap.put(p.Email__c, p);     }      List&lt;Person__c&gt; addPersons = new List&lt;Person__c&gt;();     List&lt;PersonHistory__c&gt; addPersonHistorys = new List&lt;PersonHistory__c&gt;();     List&lt;Lead&gt; addPersonLead = new List&lt;Lead&gt;();     Map&lt;String, String&gt; addPersonEmails = new Map&lt;String, String&gt;();      for(Lead lead : Trigger.new) {         if (lead.Email != null) {             if (personMap.containsKey(lead.Email)) {                 // Create PersonHistory__c record for existing Person__c records                 Person__c getPerson = personMap.get(lead.Email);                 PersonHistory__c newPersonHistory = new PersonHistory__c();                 newPersonHistory.Person__c = getPerson.Id;                 newPersonHistory.RecType__c = 'LEAD';                 newPersonHistory.RecSubType__c = lead.inq_type__c;                 newPersonHistory.SFID__c = lead.Id;                 newPersonHistory.RecTypeStatus__c = 'NEW';                 addPersonHistorys.add(newPersonHistory);             } else {                 // Create Person__c and PersonHistory__c record for NEW Person__c records                 String firstInitial = '';                 if (lead.FirstName != null) {                     firstInitial = lead.FirstName.substring(0, 1);                 }                  if (!addPersonEmails.containsKey(lead.Email)) {                     addPersonEmails.put(lead.Email, 'EMAIL');                     Person__c newPerson = new Person__c();                     newPerson.Email__c = lead.Email;                     newPerson.AltKey__c = firstInitial + lead.LastName + lead.PostalCode;                     newPerson.Current_Status__c = 'NEW';                     addPersons.add(newPerson);                     addPersonLead.add(lead);                 }             }         }     }      // INSERT NEW Person__c records     List&lt;Database.SaveResult&gt; newPersonResult = Database.Insert(addPersons);     for (integer i = 0; i &lt; newPersonResult.size(); i++) {         // Create PersonHistory__c records for new Person__c records         PersonHistory__c newPersonHistory = new PersonHistory__c();         newPersonHistory.Person__c = newPersonResult.get(i).getId();         newPersonHistory.RecType__c = 'LEAD';         newPersonHistory.RecSubType__c = addPersonLead.get(i).inq_type__c;         newPersonHistory.SFID__c = addPersonLead.get(i).Id;         newPersonHistory.RecTypeStatus__c = 'NEW';         addPersonHistorys.add(newPersonHistory);     }     insert addPersonHistorys; }   The debug log doesn't show a transaction having more than 5 out of 100 SOQL queries in the CUMULATIVE_LIMIT_USAGE sections. Not sure where to look next. Any help is appreciated.
4667
Getting error with this code but I can't figure it out  trigger LeadConvert on Lead (after insert) {     list leadsToConvert = new list();      Database.LeadConvert lc;     string convertedStatus = '';     list convertStatusList = new list();     convertStatusList = [Select Id, MasterLabel                          from LeadStatus where IsConverted=true limit 1];     if(convertStatusList.size() &gt; 0){         convertedStatus = convertStatusList[0].MasterLabel;         }     else{              convertedStatus = 'Closed - Converted';          }      for(Lead l : trigger.New){         if(l.AutoConvert__c == true){             lc = new database.LeadConvert();             lc.setLeadId(l.ID);             lc.setDoNotCreateOpportunity(true);              lc.setConvertedStatus(convertedStatus);             leadsToConvert.add(lc);         }     }      list lcrList = new list();     lcrList = Database.convertLead(leadsToConvert); }
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;}     } }
105785
Whenever an Order is inserted with Pricebook and Status of 'Activated', create a child Order_Pricebook__c record.  trigger createorderpricebook on Order (before update)  {     for(Order ce:trigger.new)     {         if(ce.status =='Activated')         {         order cf = [select id,pricebook2.id from order where id=:ce.id];         Order_Pricebook__c gh = new Order_Pricebook__c();         gh.name= 'ela';         gh.Order__c = cf.id;         gh.Price_Book__c = cf.pricebook2.id;         insert gh;         }       } }   How can I rewrite this Apex Trigger  to handle bulk operations?
36386
create table employee_tbl ( EmpID int primary key, FirstName varchar(50), LastName varchar(50), Salary float, MobileNo varchar(15) )  create table employeeaudit_tbl ( EmpID int primary key, AuditData varchar(50) )  select * from employee_tbl select * from employeeaudit_tbl  create trigger tr_employee_tbl_forinsert on employee_tbl for insert as begin         declare @EmpID int         select @EmpID = EmpID from inserted          insert into employeeaudit_tbl         values('New employee with EmpID = ' + CAST(@EmpID as nvarchar(5)) +'is added at ' + CAST(GETDATE() as nvarchar(50))) end
101111
We've had a community deployment and my brain is fried and I just whipped up a quick class that is throwing the below error. What have I done wrong here?     Error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, MSI_UserTrigger:   execution of AfterInsert caused by: System.StringException: Invalid   id: () : [] () : []: ()   What I am trying to accomplish is:   When a new user is created and is active, if they are linked to a ContactId and part of a specific profile (by name), add their ContactId to a Set&lt;ID> Then loop through contacts where the Id is in the set, and update the Community_User__c field to TRUE      Trigger:   trigger MSI_UserTrigger on User (after insert) {       if(Trigger.isAfter){          if(Trigger.isInsert){              MSIUserTriggerHandler.executeAfterInsert(Trigger.new);          }      } }      Class:   public with sharing class MSIUserTriggerHandler {     private static final String COMMUNITY_PROFILE = 'Community Knowledge User';     private MSIUserTriggerHandler() {}      public static void executeAfterInsert(List&lt;User&gt; newList){         setCreatedCommunityUsers(newList);     }      private static void setCreatedCommunityUsers(List&lt;User&gt; newList){         List&lt;User&gt; usersWithContacts = new List&lt;User&gt;();         List&lt;Contact&gt; contactsToUpdate = new List&lt;Contact&gt;();         Set&lt;ID&gt; contactIds = new Set&lt;ID&gt;();          for(User u: newList){             if(u.ContactId == null &amp;&amp; u.ContactId == ''){                 continue;             }             if((u.ContactId != null &amp;&amp; u.ContactId != '') &amp;&amp; u.Profile.Name == COMMUNITY_PROFILE &amp;&amp; u.isActive == true){                 contactIds.add(u.ContactId);             }         }          for(Contact c : [Select Id,Name,Community_User_Created__c from Contact where Id in :contactIds]){             if(!c.Community_User_Created__c){                 c.Community_User_Created__c = true;                 contactsToUpdate.add(c);             }         }         update contactsToUpdate;     } }   Am I not adding the ID correctly to the Set&lt;ID>, or am I querying wrong in my for(Contacts) loop?
123622
How how do I query recent account views and group by LastViewedDate    SELECT Id, Name                 FROM Account                ORDER BY Name DESC limit 10 FOR VIEW   I used to have it like this, but my test case is keep failing  SELECT SELECT Id, Name, LastModifiedDate                         FROM account                         WHERE LastModifiedDate !=null ORDER BY LastViewedDate DESC limit 10  static testmethod void testOppExt_TestMethod(){        Opportunity testOpp = new Opportunity(Name = 'TestOpp', StageName='Test', CloseDate = Date.today());       insert testOpp;        Account testAcc = new Account(Name = 'Test Account');       insert testAcc;        Contact con = new Contact(LastName='Test',AccountId=testAcc.id);       insert con;        Test.startTest();       OppExt testCon = new OppExt();       Contact conn = testCon.contact;       Account  Accn = testCon.acc;       Test.stopTest();     }   Error Message   Component Errors API Name Type Line Column Error Message 0 0 , Details: Average test coverage across all Apex Classes and Triggers is 0%, at least 75% test coverage is required. 0 0 SiteRegisterControllerTest.null(), Details: line -1, column -1: Previous load of class failed: oppext null 0 0 SiteLoginControllerTest.null(), Details: line -1, column -1: Previous load of class failed: oppext null 0 0 SiteRegisterController.null(), Details: line -1, column -1: Previous load of class failed: oppext null 0 0 testnewOpportunityController.null(), Details: line -1, column -1: Previous load of class failed: oppext null 0 0 SiteLoginController.null(), Details: line -1, column -1: Previous load of class failed: oppext null 0 0 testOppExt.null(), Details: line -1, column -1: Previous load of class failed: oppext null 0 0 OppExt.null(), Details: line 32, column 17: No such column 'LastViewedDate' on entity 'Account'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names. null
20439
I am trying to get this trigger to work but it is giving me an error and I am not able to figure out why. The error I am getting is "attempt to de-reference a null object)  Why trigger? We have a Destinations object which is linked to Supplier products object via a lookup relationship. There are two types of supplier products(marketplace and curated) We want to count the number of live Supplier products and put them in a separate fields(live counts for each type).  I have gotten so far to actually count the number of live products and it is giving me an error. Can any one help? I am posting the code below  Trigger code :   trigger NoOfLiveProducts on Supplier_Product__c (after insert, after Delete, after update, after undelete) {       set&lt;string&gt; destinationids = new set&lt;string&gt;();      if(trigger.isInsert) {         for(Supplier_product__c products : Trigger.new) {             destinationids.add(products.Destination__c);         }     } else if(trigger.isDelete) {         for(Supplier_product__c products : Trigger.old) {             destinationids.add(products.Destination__c);         }     }else if(trigger.isUnDelete) {         for(Supplier_product__c products : Trigger.new){             destinationids.add(products.Destination__c);         }      } else if(trigger.isUpdate) {         for(Supplier_product__c products : Trigger.new) {             destinationids.add(products.Destination__c);         }     }      if(destinationids.size() &gt; 0){         Productcounter pc = new Productcounter();         pc.updateproductCount(destinationids);     }    }   Class code :  public class Productcounter {      public void updateproductcount(set&lt;string&gt; productIDs) {           if(productIDs == null){                return;         }          if(productIDs.size() == 0){             return;         }           list&lt;Supplier_Product__c&gt; ProductList = new list&lt;Supplier_Product__c&gt;();         ProductList = [Select ID,Destination__c                     From Supplier_Product__c                     Where Destination__c = :productIDs];          integer totalCount;         map&lt;string, integer&gt; DestinationIDToProductCountMap = new map&lt;string, integer&gt;();                for(Supplier_product__c ProductItem : ProductList){             if(DestinationIDToProductCountMap.containsKey(ProductItem.Destination__c)){                 totalCount = DestinationIDToProductCountMap.get(ProductItem.Destination__c);             }else{                 totalCount = 0;             }             totalCount += 1;             DestinationIDToProductCountMap.put(ProductItem.Destination__c, totalCount);         }          list&lt;Destination__c&gt; DestinationUpdateList = new list&lt;Destination__c&gt;();         Destination__c DestinationTemp;         for(string ProductID : DestinationIDToProductCountMap.keySet()){             DestinationTemp.ID = ProductID;             DestinationTemp.No_of_Live_Curated_Products__c = DestinationIDToProductCountMap.get(ProductID);             DestinationUpdateList.add(DestinationTemp);         }         if(DestinationUpdateList.size() &gt; 0){             update DestinationUpdateList;         }           }           }
33868
Hi i have written trigger in which SC_Problem_Management__c is parent object and SC_Problem_Case_Link__c is child object having master detail relationship. I want to update status field of parent object to awaiting deployment when all child records status having value as 'Tested'.  trigger updatestatus on SC_Problem_Case_Link__c(after update) {     List&lt;SC_Problem_Management__c&gt; parentObjList = new List&lt;SC_Problem_Management__c&gt;();     List&lt;SC_Problem_Management__c&gt; parentObjListToBeUpdated = new List&lt;SC_Problem_Management__c&gt;();     public List&lt;Id&gt; listIds = new List&lt;Id&gt;();     for (SC_Problem_Case_Link__c childObj : Trigger.new) {         listIds.add(childObj.SC_Problem_Management__c);     }     parentObjList = [SELECT Id,Status__c, (SELECT ID, Status__c FROM SC_Problem_Case_Link__r) FROM SC_Problem_Management__c WHERE ID IN :listIds];     Boolean checkApproval = TRUE;     for (SC_Problem_Management__c bid : parentObjList) {         for (SC_Problem_Case_Link__c bsaa : bid.SC_Problem_Case_Link__r) {             if (bsaa.Status__c == 'Tested') {                 checkApproval = TRUE;             } else {                 checkApproval = FALSE;             }         }         if (checkApproval == TRUE) {             bid.Status__c = 'Awaiting Deployment';         }         parentObjListToBeUpdated.add(bid);     }     if (parentObjListToBeUpdated.size() &gt; 0) {         update parentObjListToBeUpdated;     } }   I am getting error while saving the trigger. "Error    Error: Compile Error: Status__c,(SELECT ID, Status__c FROM SC_Problem_Case_Link__r) FROM SC_Problem_Management__c ^ ERROR at Row:1:Column:48 Didn't understand relationship 'SC_Problem_Case_Link__r' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names. at line 9 column 21"  Please guide on this issue.