I am using PB to check if the Case record is new, and if the Account field is Not blank and a Case.Account.picklist__c has a Certain value then update priority.  SO, my evaluation criteria are -   AND ( ISNEW() , NOT(ISBLANK([Case].AccountId )) , ISPICKVAL([Case].Account.picklistA__c , 'ABC')  )     If all these conditions meet, I am updating the case priority.  But, when I create a Case record, where Account is blank, It throws an error -  The flow failed to access the value for myVariable_current.Account.piclistA because it hasn't been set or assigned.
123280
Note: This error might look like a familiar error but the   resolution mentioned in the  is not working in the below case and I am not sure why, hence posting this question.   Problem description:   I have a process builder on case object set to fire for every time new record is created. Criteria is set to 'Formula evaluates to True' with below formula: AND(NOT(ISBLANK([Case].AccountId)),ISPICKVAL([Case].Account.Active__c,'Yes')) With immediate action set to update custom field on the Case object. Custom field Active__c on the Account object is type picklist with two possible values 'yes' and 'no'.   Screenshots of the process builder:        Creating a case as shown in the below screenshot with very minimal details and especially not populating account details:    Throws below error:     The flow failed to access the value for   myVariable_current.Account.Active__c because it hasn't been set or   assigned.   Relevant data from log file:     22:14:31.0 (12479016)|WF_FLOW_ACTION_BEGIN|09L370000000FEJ 22:14:31.13   (13607478)|FLOW_CREATE_INTERVIEW_BEGIN|00D37000000H8hr|300370000008ZTl|301370000004weE   22:14:31.13   (15394571)|FLOW_CREATE_INTERVIEW_END|5525dfa7819c33f438ce3cef9b6c15c668d8ff2-3d11|Test   22:14:31.15 (15820974)|FLOW_START_INTERVIEWS_BEGIN|1 22:14:31.15   (16674702)|FLOW_START_INTERVIEW_BEGIN|5525dfa7819c33f438ce3cef9b6c15c668d8ff2-3d11|Test   22:14:31.15 (35470120)|FLOW_ELEMENT_ERROR|The flow failed to access   the value for myVariable_current.Account.Active__c because it hasn't   been set or assigned.|| 22:14:31.15   (35479812)|FLOW_START_INTERVIEW_END|5525dfa7819c33f438ce3cef9b6c15c668d8ff2-3d11|Test 22:14:31.15 (35517783)|FLOW_START_INTERVIEWS_END|Interview error.   Aborting all.|5525dfa7819c33f438ce3cef9b6c15c668d8ff2-3d11|Test   22:14:31.15 (35528335)|FLOW_START_INTERVIEWS_END|1 22:14:31.0   (35588898)|WF_FLOW_ACTION_ERROR|09L370000000FEJ|300370000008ZTl|Error   executing flow: test, FlowDefId: 300370000008ZTl, FlowVersionId:   301370000004weE 22:14:31.0   (35612585)|WF_FLOW_ACTION_ERROR_DETAIL|An unhandled fault has   occurred in this flowAn unhandled fault has occurred while   processing the flow.  Please contact your system administrator for   more information. 22:14:31.0   (35683203)|WF_FLOW_ACTION_END|09L370000000FEJ   URL to the complete debug log :  (Note: You can see from the log that there are no other workflow rules or triggers on the case object).  My analysis: When the first condition inside the AND expression is evaluating as false, why is it trying to evaluating the second condition to check the custom field on the Account object? It shouldn't right?  Any help?  EDIT: I am looking to solve this using option 'Formula Evaluates to True' only because I have other complex criteria like checking the day(Mon vs Tue and etc) of the case creation.
53086
I have written a trigger for before update and after insert function  trigger EstimateBudgetPerMonth on Opportunity__c(after insert, before update) {     Date startDate = Date.newInstance(2008, 1, 1);     Date endDate = Date.newInstance(2008, 1, 30);     Set &lt; Id &gt; oppId = new Set &lt; Id &gt; ();     Integer totalBudget;     for (Opportunity__c opp: Trigger.new) {         startDate = opp.Campaign_Start_Date1__c;         endDate = opp.Campaign_End_Date1__c;         totalBudget = Integer.valueOf(opp.Budget1__c);         oppId.add(opp.Id);     }      InsertBudgetOpp insertRec = new InsertBudgetOpp();     InsertBudgetOpp updateRec = new InsertBudgetOpp();        if (Trigger.isInsert) {         System.debug('--===Insert==--#--===Insert==--#--===Insert==--');          List &lt; Budget_Allocation__c &gt; baList = insertRec.insertChild(oppId, startDate, endDate, totalBudget);          insert baList;      } else if (Trigger.isUpdate) {         System.debug('--===Update==--#--===Update==--#--===Update==--');          Map &lt; String, Budget_Allocation__c &gt; baNewMap = updateRec.updateChild(oppId, startDate, endDate, totalBudget);          upsert baNewMap.values();     }    }    Its throwing the below error.     Error: Invalid Data.  Review all error messages below to correct your   data. Apex trigger EstimateBudgetPerMonth caused an unexpected   exception, contact your administrator: EstimateBudgetPerMonth:   execution of BeforeUpdate caused by: System.DmlException: Upsert   failed. First exception on row 0 with id a0Up00000000FHJEA2; first   error: SELF_REFERENCE_FROM_TRIGGER, Object (id = a06p0000000N3WU) is   currently in trigger EstimateBudgetPerMonth, therefore it cannot   recursively update itself: []: Trigger.EstimateBudgetPerMonth: line   38, column 1
14766
I need to evaluate the current user running a flow. Someone suggested I use the Global Variable {!User.Id}, but it's returning a 15 digit Id. I need to compare the current user with the Account owner. The Account Owner field is returning an 18 digit id. Is there another way to evaluate the current user in my flow and compare it to an Account owner?   The above resolution doesn't really work for my purposes for evaluating a user if I can't compare the user to the Account Owner ID. In the above example, the Account Owner will never = the current user as it is comparing a 15 digit id to a 18 digit id.  Is there a way turn the User ID from the Global Variables into 18 digits? Or vice versa, make the Account Owner ID return as 15 digits? Thanks so much!
73694
I have used the following code to add new picklist values to the picklist field called "Tags__c" in contact object. The code works and the new picklist values are getting created successfully but they are not added to any record types and hence i have to manually add them to the record types to view the new values in UI. I need to do assign the existing record types for the new picklist values created through apex metadataservice code.  public static void updatePicklist() {     MetadataService.MetadataPort service = new MetadataService.MetadataPort();                  service.SessionHeader = new MetadataService.SessionHeader_element();     service.SessionHeader.sessionId = UserInfo.getSessionId();     MetadataService.CustomField customField = (MetadataService.CustomField) service.readMetadata('CustomField', new String[] { 'Contact.Tags__c' }).getRecords()[0];     metadataservice.PicklistValue two = new metadataservice.PicklistValue();     two.fullName= 'Sample 1';     two.default_x=false;     metadataservice.PicklistValue three = new metadataservice.PicklistValue();     three.fullName= 'Sample 2';     three.default_x=false;     customField.picklist.picklistValues.add(two);     customField.picklist.picklistValues.add(three);   handleSaveResults(     service.updateMetadata(         new MetadataService.Metadata[] { customField })[0]);    }   Can someone suggest me a solution for this?
109966
i have posted this question earlier but i'm not getting the proper solution  please read the requirement carefully.* i have a custom object Integration__c and it has fields username__c,password__c,url__c,account__c(lookup field) fields. and Integration__c has some records.   here comes my requirement is i have created a trigger on Case object as after insert event. 1.when case creating must be select an account lookup field with one salesforce account. 2.now after clicking the save button it will check with Integration__c custom object records with the matching account field in case record. 3.if any record is in the Integration__c is match with the case object account field then returns the field values of integration__c from that record only. for that i have developed a trigger on Case : trigger Type on Case (after Insert) {      List&lt;ID&gt; cIds = new List&lt;ID&gt;();           Set&lt;String&gt; lst_accountName = new Set&lt;String&gt;();     List&lt;String&gt; allaccountnamesList = new List&lt;String&gt;();          //Map&lt;ID, Integration__c&gt; mapIds = new Map&lt;ID,  Integration__c&gt;();                           for(Case cObj : Trigger.new){                        if(cObj.Account.Name != null &amp;&amp; cObj.IntegrationTo__c != null){                                cIds.add(cObj.Id);                                } lst_accountName.add(cObj.Account.Name);                        }allaccountnamesList.addAll(lst_accountName );                  List&lt;Case&gt; cas = Trigger.new;          List&lt;Integration__c&gt; listAll = [SELECT id,name,username__c,password__c,URL__c,account__c,integrationwith__c FROM Integration__c ];                      for(Case c : cas  ){             for(integer i=0; i&lt;=listAll.size();i++){                     if(listAll.get(i).IntegrationAccount__c.contains(c.Account.Name)){                                                                                                                                          String name = listAll.get(username__c);                      String pwd = listAll.get(password__c);                      String url = listAll.get(URL__c);                                                                        }        }    } }  How can I get the only matched account field value on case with any of the records in Integration__c, then return the record  details from that record only? when i saving the above code it shows an error called :  Error: Compile Error: Variable does not exist: username__c at line 32 column 48
854
I am trying to copy the value of user selected Status value into the standard salesforce required Company field. Now, when I try to save the record on the object since I am not entering any value in the Company field, the record is not being saved. How do I solve this kind of issue? Any leads appreciated  trigger CopyStatusToTitle on Lead (before insert, after insert) {      List&lt;Lead&gt; leadList = new List&lt;Lead&gt;();     if(Trigger.isInsert){         if(Trigger.isBefore){             //process before insert               for(Lead l : trigger.New){                 l.Company = l.Status;              }          }else if(Trigger.isAfter){             //process after insert          }       } }
23293
I want to create a case which has an attachment, Billing Account, and topics. Given below is the code from my Test Class:  Scenario: Once user submit the case request and ask for approval. The request goes to the Manager for approval, once the request approves, an email goes to Legal team with an Case attachments in an email.  Topic__c tc = new Topic__c(Name ='My New topic'); Attachment att = new Attachment(Name = 'sample.pdf');  Case c = new Case(Origin = 'Phone',                           Subject = 'New Testing',                           Department__c = 'XXXXXXX', Priority = 'Normal',                           Topic__c = tc.Id,                           Risk_Approval__c = true); insert c;   I am getting the below error:     System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CaseTrigger: execution of BeforeInsert   My Trigger class:  trigger sendEAttachmentsInMail on Case (before insert, before update){  for(Case casevar : Trigger.new){          Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();          mail.setBccSender(false);         mail.setUseSignature(false);         mail.setTargetObjectId(casevar.Id);         mail.setTemplateId('XXXXXXXXX');         mail.saveAsActivity = false;        //Set email file attachments         List&lt;Messaging.Emailfileattachment&gt; fileAttachments = new List&lt;Messaging.Emailfileattachment&gt;();         for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :casevar.Id])         {         // Add to attachment file list         Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();         efa.setFileName(a.Name);         efa.setBody(a.Body);         fileAttachments.add(efa);         }         mail.setFileAttachments(fileAttachments);       //Send email         Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });          } }
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); }
66308
The environment setup is as follows: 1) there is a workflow triggered by some criteria which has a time dependent action which will update a field on the object. 2) With apex-code I update a List of 10 of such objects so that the criteria will fire for all of them  When the time countdown expires, will there be 10 different transactions or will there be 1 transaction with the 10 objects?
101869
I have one recordtype named 'India' in both Account and Contact Objects.My requirement is whenever i create a new account record of type 'India' a new contact record of type 'India' should be created automatically.  i tried with the following code:  trigger AccRecTypeTrigger on Account (before insert) {     List&lt;RecordType&gt; recType = [select id,name from RecordType where sobjectType = 'Account' and isActive = true];    Map&lt;String,Id&gt; m = new Map&lt;String,Id&gt;();    for(RecordType r : recType){      m.put(r.name,r.id);    }     List&lt;Contact&gt; conlst = new List&lt;Contact&gt;();    for(Account a : trigger.new){        a.recordTypeId = m.get('India');        Contact con = new Contact();        con.accountId = a.id;        con.recordTypeId = a.recordTypeId;        con.recordType.name = a.recordType.name;         conlst.add(con);       }    insert conlst; }   But i am getting following error when i try to save     Apex trigger AccRecTypeTrigger caused an unexpected exception, contact   your administrator: AccRecTypeTrigger: execution of BeforeInsert   caused by: System.NullPointerException: Attempt to de-reference a null   object: Trigger.AccRecTypeTrigger: line 14, column 1   Please help me how to achieve this......
82893
Is it true that I cannot have OR or AND operators in if statements in APEX?  I have an object that has a picklist Code__c, and I need to execute some code if the code is set to either A or B.  How would I write something like:  if(pc.Code__c = 'A' || pc.Code__c = 'A') { }   Tia.
16290
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, navigate to the  tag. This question and answer is owned by the community! If you can improve it and make it more useful, you're welcome to edit it. I am building a trigger, a unit test, or other Apex code. I'm working with sObject records, and trying to access related record information. For example, I might have a structure like this: Account a = new Account(Name = 'Test'); insert a;  Opportunity o = new Opportunity(Name = 'Donation', AccountId = a.Id); insert o;  System.assertEquals(o.Account.Name, 'Test', 'Correct Account associated'); // Assertion fails!  Or, in a trigger, I might be aiming for something like this: trigger ContactTrigger on Contact (after insert) {     for (Contact c : Trigger.new) {         if (c.Account.Name == 'Test') {             // Take some action here         }      } }  Why doesn't this work? Why am I getting null values, or NullPointerExceptions?
33419
Financial Account is a child of Client in a Master-Detail relationship. The client (John Sandbox) has a Wealth Advisor, 'John Smith', on his client record, however, the system debug that pulls finAcct.client__r.Wealth_Advisor__c shows this field as 'null'.  Does anyone have any idea why I am not getting the value in this field? The goal of this trigger is to make sure that the lookup fields for the Client Team (one of which is 'Wealth Advisor') always match between the client record and the financial account record when they are linked. Thanks!      Boolean UpdateMe;     List &lt;Financial_Account__c&gt; FinAcctsToUpdate = new List&lt;Financial_Account__c&gt;();      //Loop through all Financial Accounts in Trigger.new     for(Financial_Account__c finAcct : newFinAccts){         UpdateMe = false;          System.debug('finAcct WA Lookup: ' + finAcct.Wealth_Advisor_Lookup__c);         System.debug('Client: ' + finAcct.client__c);         System.debug('Acct WA: ' + finAcct.client__r.Wealth_Advisor__c);          if (finAcct.Wealth_Advisor_Lookup__c != finAcct.client__r.Wealth_Advisor__c){             finAcct.Wealth_Advisor_Lookup__c = finAcct.client__r.Wealth_Advisor__c;             UpdateMe = true;         }         if(UpdateMe == true){             FinAcctsToUpdate.add(finAcct);         }         UpdateMe = false;     }      if(FinAcctsToUpdate.size() &gt; 0 ){         update FinAcctsToUpdate;     }
57540
I'm trying to update an account list and I need to get the Ids when the update fails.  I use the getId() method but for accounts which fail I get null.  It's an update so my account already has an Id.  Is it normal ? If it is, how can I get the Ids list of non-updated accounts ?  Here is my code :  List&lt;Account&gt; accountsList = [select Id from Account];  for(Account a : accountsList) {     a.Name = 'Test', }  List&lt;Database.SaveResult&gt; res = Database.update(accountsList, false);  for (Database.SaveResult s : res) {     if (!s.isSuccess()) {         system.debug(s.getId()); // I get null here      }  }
176
I want to check whether a certain criteria is met or not using a trigger before inserting a record. if it meets the criteria, i insert the record, but if it does not i want to display an error message that it doesn't meet the criteria. how do i do it? Please help if anyone knows.
115907
I am trying to addError on the opportunities based on one condition. But getting System.FinalException: SObject row does not allow errors error while saving the record. Below I have given the code snippet. Please let me know how I can resolve the issue.  if(Trigger.isUpdate &amp;&amp; Trigger.isBefore){         map&lt;Id,Opportunity&gt; newOpptyMap = (map&lt;Id,Opportunity&gt;)trigger.newMap;         OpportunityTriggerHelper.checkforStageDuration(newOpptyMap,Trigger.OldMap);     }   The function is below where I am adding the error statement  public static void checkforStageDuration(Map&lt;Id,Opportunity&gt; oldMap, Map&lt;Id,Opportunity&gt; newMap){         Map&lt;Id,Opportunity&gt; recordsToCheck = new Map&lt;Id,Opportunity&gt;();         for(Id oppId : newMap.keyset()){             if(newMap.get(oppId).StageName != oldMap.get(oppId).StageName){                 recordsToCheck.put(oppId,newMap.get(oppId));             }         }         List&lt;Opportunity_Stage_History__c&gt; oppStageHistory = [select Id,Expected_Stage_Duration__c,Opportunity__c,Duration__c,Reason_For_Delay__c from Opportunity_Stage_History__c where Opportunity__c IN :recordsToCheck.keyset()];         for(Opportunity_Stage_History__c oppHistory : oppStageHistory){             if(oppHistory.Duration__c&gt;oppHistory.Expected_Stage_Duration__c &amp;&amp; oppHistory.Reason_For_Delay__c==null){                 newMap.get(oppHistory.Opportunity__c).addError('The Opportunity has crossed it\'s Stage Duration, Please fill the Reason for Delay !!');             }         }     }
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); }