I have a custom object "Opportunity Project", and Opportunity has a lookup to the custom object. Each "Opportunity Project" could have a handful of Opportunities related to it. Need a basic trigger that grabs the total of the Opportunity Amounts and updates a currency field on the Opportunity Project record. (Cannot make Opportunity a Child under a custom object)
123517
Is there anyway to update a rollup summary field with lookup relation ship for a custom object. How can we achieve this using triggers ?
76405
I want to update the field in multiple records based on the unique_pile_id__c that is unique for all the multiple records. I am trying to write trigger like this:  trigger opMetricsTrigger on Operational_Metrics__c (before insert,before update)  {     Operational_Metrics__c[] op=null;     Set&lt;Id&gt; opIds = new Set&lt;Id&gt;();     public static boolean run = true;      if(run)     {         run=false;         for (Operational_Metrics__c e : Trigger.new)          {             if(e.Unique_Pile_ID__c != null)                 opIds.add(e.Unique_Pile_ID__c );         }          Map&lt;Id, Operational_Metrics__c&gt; y =              new Map&lt;Id, Operational_Metrics__c&gt;([select Unique_Pile_ID__c,unique_id__C,                  Project__c,Composting_Method__c,Pile_Monitoring_Date__c,Average_Temperature__c,                 Moisture_Test__c,Pile_Monitoring_Action_Taken__c,Other_Action__c,                 Pile_Input_Register_Date__c,Total_Waste_Input_on_the_Pile__c,                 Pile_Completion_Stage__c,Date_Pile_COmpleted__c,Curing_Batch_Register_Date__c,                 No_of_Days__c  from operational_metrics__c                  where Unique_Pile_ID__c in :opIds]);          for (Operational_Metrics__c oc : [select Unique_Pile_ID__c,unique_id__C,              Project__c,Composting_Method__c,Pile_Monitoring_Date__c,Average_Temperature__c,             Moisture_Test__c,Pile_Monitoring_Action_Taken__c,Other_Action__c,             Pile_Input_Register_Date__c,Total_Waste_Input_on_the_Pile__c,             Pile_Completion_Stage__c,Date_Pile_COmpleted__c,Curing_Batch_Register_Date__c,             No_of_Days__c  from operational_metrics__c where Unique_Pile_ID__c in :opIds])          {             System.debug('oc '+y.get(oc.Unique_Pile_ID__c));         }       } }   But when I am saving a record it is throwing:      execution of BeforeUpdate caused by: System.StringException: Invalid id: 10-Ber1: External entry point    Here 10-Ber1 is the unique_pile_id__c. Could anyone help me out?
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.
111931
I am new to Apex and just starting to understand using maps to avoid loops within loops and hitting limits. My trigger below updates opp line items with the internal cost from another object using a map and the one value - "Service_Name".  My issue is I need to update another field on the Opp line item with "Agent Fee" in the same way  - but there are 4 criteria to get the right Agent Fee from another object. I cant see how do so this other than have a loop of agent Fees object with the opp line loop? How else can I do this? Is it possible with Maps ?  trigger sectortest on Opportunity (after update) {          for (Opportunity eachopportunity : Trigger.new){                                        //Get costs for the Opps FY and put in map         List&lt;Internal_Costs__c&gt; costs = [SELECT Id, Financial_Year__c, Service_Name__c, Standard_Cost__c  FROM Internal_Costs__c WHERE Financial_Year__c =: eachopportunity.Financial_Year__c];          Map&lt;string, Decimal&gt; costmap = new Map&lt;string, Decimal&gt;();         for (Internal_Costs__c eachcost : costs){                                         costmap.put(eachcost.Service_Name__c, eachcost.Standard_Cost__c);                         }                 //Get Line Items for Opp         List&lt;OpportunityLineItem&gt; opplines = new List&lt;OpportunityLineItem&gt;();           opplines = [SELECT Id, DS_Status__c, Country__c, Product2Id, UnitPrice FROM OpportunityLineItem WHERE OpportunityId =: EachOpportunity.Id];           List&lt;OpportunityLineItem&gt; opplinesupdate = new List&lt;OpportunityLineItem&gt;();                //assign cost to line items              for (OpportunityLineItem EachOppline : opplines) {                                                                                              decimal cost = costmap.get(EachOppline.Service_Name__c);                                                                 EachOppLine.Internal_Cost__c = cost;                                                                             opplinesupdate.add(EachOppline);                                                                                                                                                        }              update opplinesupdate;                        }                       }
39132
I created a custom button for custom object to place in the related list. The custom object has two look-ups, one for case and one for account. This button, when clicked, should open in a new window to save a record of the custom object, with the default values for each look-up to populate automatically depending on the record where the button was clicked. It works for every record so far, except one case. It then throws the error: A problem with the Onclick Javascript for this button or link was encountered: Unexpected identifier.  I couldn't find any differences between records where it works and doesn't.  Code:  window.open('a2U/e?CF00N600000037HI4={!Account.Name}&amp;CF00N600000037HI4_lkid={!Account.Id}&amp;retURL=%2F{!Account.Id}&amp;CF00N600000037HI5={!Case.CaseNumber}&amp;CF00N600000037HI5_lkid={!Case.Id}&amp;retURL=%2F{!Case.Id}','','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=yes,location=yes,status=yes');
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;         }           }           }
88953
Is there a good tool that checks the schema to determine custom fields and their use in triggers, page layouts, classes, etc? We have a couple objects that are getting close to the 500 max and it would be nice if there were a better way than having someone get a list of custom fields for an object manually and then searching every page layout, class, and trigger for use of each field.
66803
I am trying to call my Apex class from a trigger:  trigger newCrossSellAccounts on Account (before insert) {    crossSellModule.insertAfterAccount2(trigger.new); }   On the class I have:  public void insertAfterAccount2(list&lt;account&gt; accountList){   When I try to save trigger I get error:  Method does not exist or incorrect signature: crossSellModule.insertAfterAccount2(LIST&lt;Account&gt;) at line 2 column 4    Now from  it says .new "Returns a list of the new versions of the sObject records." I tried to change the function on class to:  public void insertAfterAccount2(sObject&lt;account&gt; accountList){   But I get error:  Invalid type: sObject&lt;account&gt;    Should I loop thru and create a list in trigger first? Or is there are workaround. Also, how one would test such trigger/class combination?
82116
Since I started coding in Apex, I've gotten used to working with lists of IDs of objects not the objects themselves.  This time around, instead of creating a List&lt;ID&gt; of account ids, I created a List&lt;Account&gt;.  Now, I'm trying to add account records to this list, via a lookup field on a related custom object. However, when I do this, I get an error back telling me I'm trying to add an ID to an sObject list.   So what I'm wondering is, how would I best indicate that it's the sObject record as a whole I want to add, not just the ID indicated by the lookup field? And if it involves a SOQL query, wouldn't that be problematic in terms of hitting governors limits?
12448
I have a custom object with name and a lookup to contact among other fields.  The need that i have is that i need to make sure that only record name should not be duplicated for a contact.  There can be duplicate names as long as its not the same contact. We should not allow duplicate names for the same contact.  Can we achieve this using validation rules? I am trying to avoid using triggers if this can be achieved using validation rules.
79320
For example, my component has the following section that displays a record form:  &lt;template if:true={showRecordForm}&gt;     &lt;lightning-record-form         object-api-name={sObjectApiName}         onsuccess={handleFormSuccess}         record-type-id={recordTypeId}         layout-type="Full"         columns="2"         oncancel={handleFormCancel}         onload={handleFormLoad}&gt;     &lt;/lightning-record-form&gt; &lt;/template&gt;   It will load the form for the object I specify in sObjectApiName, and with the specified record type as well. The problem is that I want to assign some values to specific fields.  Let us say that it is a Case form, and I want to assign an Account ID to the AccountId field, before the case is submitted to the platform.  I tried to query the lightning-input-fields, but with no success:  const inputFields = this.template.querySelectorAll(     'lightning-input-field' ); if (inputFields) {     inputFields.forEach(field =&gt; {         console.log(field)     }); }   This is a snippet from the .  I'm starting to think that this might not be viable, or too much trouble. Is there a way to do this?
47396
I have a Child and parent case. I have the following fields:   Reopen Flag (Checkbox field) Case Reopened By (Drop down field)   The vales in Reopened By fields are Customer and Internal  Total Reopen Count Customer Reopen Count Internal Reopen Count   Details by Steps:   Select Reopen Flag in Child Case Select Case Reopened By (Value: Customer) in Child Case Customer Reopen Count Field gets incremented by 1. in Child Case Total Reopen Count gets Incremented by 1. in Child Case Parent Case also gets updated.   Repeat the steps but it does not gets updated in Parent Case.  Change the Value in Case Reopened By - "Internal" in child Case then the values will get updated in Parent Case.  How to update Parent Case from child case every time Total Reopen Count and Customer Reopen Count/Internal Reopen Count gets updated.  trigger Update_Parent_Case on Case (after update) {      map&lt;string,case&gt; case_map = new map&lt;String,Case&gt;();      for(case cs : trigger.new){          if(trigger.oldMap.get(cs.id).Total_Reopen_Count__c != cs.Total_Reopen_Count__c){                         case_map.put(string.valueof(cs.ParentId),cs);         }     }       list&lt;case&gt; to_update = new List&lt;case&gt;();     if(case_map.size() &gt; 0){         for(case cc : [Select id,Case_Re_opened_By__c,Re_open_Flag__c, Customer_Re_open_Count__c,Internal_Re_open_Count__c from case where id in: case_map.keySet()]){             case c = case_map.get(cc.id);               cc.Case_Re_opened_By__c = c.Case_Re_opened_By__c;              cc.Re_open_Flag__c = true;             cc.Total_Reopen_Count__c = c.Total_Reopen_Count__c;             cc.Customer_Re_open_Count__c = c.Customer_Re_open_Count__c;                cc.Internal_Re_open_Count__c = Internal_Re_open_Count__c;               to_update.add(cc);         }         update to_update;         case_map.clear();     }  }
110197
I have a child form and I want to get the total of the child forms to update the parent with the sum total. I am struggling with the CAML query to get the total back. The below returns zero records at present because (i suspect) the query isn't quite right.          var query = '&lt;Query&gt;&lt;Where&gt;&lt;Eq&gt;&lt;FieldRef Name="Engagement" /&gt;&lt;Value Type="Lookup"&gt;';             query += ParentEngagementID + ";#" + ParentEngagementText + "&lt;/Value&gt;&lt;/Eq&gt;&lt;/Where&gt;&lt;/Query&gt;";           console.log("Query is " + query);         //Checked in chrome this is: Query is &lt;Query&gt;&lt;Where&gt;&lt;Eq&gt;&lt;FieldRef Name="Engagement"&gt;&lt;/FieldRef&gt;&lt;Value Type="Lookup"&gt;106;#ABC Ltd - 31/03/2016 - Year End&lt;/Value&gt;&lt;/Eq&gt;&lt;/Where&gt;&lt;/Query&gt;          var viewFields = '&lt;ViewFields&gt;&lt;FieldRef Name="Budget_x0020_hours" /&gt;&lt;FieldRef Name="Actual_x0020_hours" /&gt;';             viewFields += '&lt;/ViewFields&gt;';          var NewBudgetTotal = 0.00;         var NewActualTotal = 0.00;         $().SPServices({             operation: "GetListItems",             async: false,             listName: "Work tracker - Products",             webURL: "/sites/UKIAsuDataAnalytics",             CAMLViewFields: viewFields,             CAMLQuery: query,             completefunc: function (xData, Status) {                 console.log("---------------------");                 console.log(status);                 console.log(xData.responseText);                 console.log("---------------------");                 $(xData.responseXML).SPFilterNode('z:row').each(function() {                     console.log('Processing list of returned CAML items');                     if($(this).attr("ows_Budget_x0020_hours")) {                         NewBudgetTotal += Number(parseFloat($(this).attr("ows_Budget_x0020_hours").split(";#")[0],2).toFixed(2));                     }                     if($(this).attr("ows_Actual_x0020_hours")) {                         NewActualTotal += Number(parseFloat($(this).attr("ows_Actual_x0020_hours").split(";#")[0],2).toFixed(2));                      }                 });             }         });   If I comment out the query the XML responses coming back are like the below, and you can see the Engagement field should match:      "&lt;z:row ows_Budget_x0020_hours='3.00000000000000' ows_Actual_x0020_hours='0' ows_MetaInfo='80;#' ows__ModerationStatus='0' ows__Level='1' ows_ID='80'      ows_UniqueId='80;#{E91295D7-EF93-4F11-B486-E00F6A6AB7DF}' ows_owshiddenversion='16' ows_FSObjType='80;#0' ows_Created='2016-07-13 10:17:15' ows_PermMask='0x7fffffffffffffff' ows_Modified='2016-08-26 18:58:30'      ows_Engagement='106;#ABC Ltd - 31/03/2016 - Year End' ows_FileRef='80;#sites/MySite/Lists/Work Tracker  Tools/80_.000' /&gt;"   I have tried all sorts of changes to the query for the content of "Engagement" but nothing helps. Any thoughts?  (Please don't blame me on design here - I am trying to patch up some Sharepoint "work" done by a colleague. I am certainly not the best person to do the patchup, as much as they weren't the person do to the work.)
67910
I would like to define a workflow whose rule criteria is that a Lookup field changed, but ISCHANGED and PRIORVALUE generate syntax errors. Both generate the message     Error: Function (PRIORVALUE|ISCHANGED) may not be used in this type of formula   Is it possible for a workflow to determine when a Lookup has changed or is the Trigger territory?
59774
I have custom object called candidate. I have created field name called first name which is read-only in the page layout. Once a record is created with first name field populated I am able to edit that field. Why I am able to edit (I mean getting pencil icon). Can anyone suggest me for this issue?
8484
I have an apex trigger that involves querying multiple objects. But I encounter this kind of error :      Error: Compile Error: A non foreign key field cannot be referenced in   a path expression: ObjectBs__r   Here's a portion of the trigger where I encounter such error message:   Set&lt;Id&gt; objAid = new Set&lt;Id&gt;();  Set&lt;Id&gt; objDid = new Set&lt;Id&gt;();  for(ObjectC__c c : Trigger.new) {         objAid.add(c.ObjectA__c);    }  List&lt;ObjectA__c&gt; objAList = [SELECT Id, Name, (SELECT Id, Name, ObjectD__c FROM ObjectBs__r) FROM ObjectA__c WHERE Id IN: objAid];  for(ObjectA__c a : objAList[0].ObjectBs__r) {         objDid.add(a.ObjectBs__r.ObjectD__c); }
62150
I need to be able to detect that the trigger execution is happening because of a workflow field update. There is a suggestion in the cookbook:  But this solution is not properly bulkified. If my batch of records is split up (200, 100, 50 whatever the server decides) the 2nd to nth batches are not processed correctly because the flag has already been set. The second part of the problem is: This is part of a managed package. I have no control of the customer's workflow rules, supporting and configuring a flag/last changed field on a record is not realistic, our company doesn't have the support resources to be walking each customer through the configuration. Has anyone been able to solve this problem for large batches of records? Edit (In Response to Calebs Answer) Separate trigger batches do not run in separate contexts trigger AccountTriggerContext on Account (before insert) {     System.debug('counter='+TriggerContextCounter.getCounter()); }  . global without sharing class TriggerContextCounter {      private static Integer counter = 0;          public static Integer getCounter() {         Integer value = counter;         counter++;         return value;     }      private static testMethod void testTriggerContexts() {         List&lt;Account&gt; accounts = new List&lt;Account&gt;();         for(Integer i = 0; i &lt; 250; i++) {             accounts.add(new Account(Name='testTriggerContexts: ' + i));         }         insert accounts;     } }  Unit test debug messages  USER_DEBUG|[2]|DEBUG|counter=0 USER_DEBUG|[2]|DEBUG|counter=1  Both counters should have been 0 if the batches were running in separate contexts Edit Further explanation of background for @Ralph This is a generalized explanation, but when certain conditions are met, some date fields on other objects are updated. The trigger runs and updates the dates. If a workflow rule causes a field update on the object, the same trigger is run again and the dates on the other objects are updated for a second time. And because this is an increment operation the dates on the other objects are off by a factor of 2.