I've created a custom object for Leaves which allows the users under my org to apply for leaves. I've added three types of leaves such as Casual Leave, Sick Leave &amp; Leave without Pay. I've used an Apex Trigger to check and limit the creation of only one record by one user per day but this Apex is creating a problem in org because it isn't allowing the users to apply for pre-planned leaves, i.e. if a user is applying for Sick Leave for the day he/she should also be allowed to apply for other leaves like Casual &amp; Unpaid for different dates on the same day.  Fields I've used:    Start_Date__c (Date type) End_Date__c (Date type) Leave_Type__c (Picklist type)   I want to use a trigger dependent on the Start_Date__c &amp; Leave_Type__c  The Apex Currently in use:  trigger LeaveRecordDuplicateTrigger on New_Casual_Leave__c (before insert) {     for(New_Casual_Leave__c a:Trigger.new)     {         string uid = userinfo.getName();         List&lt;New_Casual_Leave__c&gt; acc=[select Id, CreatedDate, Contact__r.Account.Name,   Start_Date__c, Leave_Type__c from New_Casual_Leave__c                                          where (Contact__r.Account.Name = :uid                                          AND CreatedDate = TODAY)                                          and Leave_Type__c =a.Leave_Type__c];            if(acc.size()&gt;0)            {                a.adderror('One leave is already applied for the Day For ' + uid);            }        }    }   //Getting error while using the above code: Error: Compile Error: Unexpected token 'a.Leave_Type__c'. at line 5 column 229   What changes to be made to avoid errors? Where am I going wrong?
122220
I've created a custom object for Leaves which allows the users under my org to apply for leaves. I've added three types of leaves such as Casual Leave, Sick Leave &amp; Leave without Pay. I've used an Apex Trigger to check and limit the creation of only one record by one user per day but this Apex is creating a problem in org because it isn't allowing the users to apply for pre-planned leaves, i.e. if a user is applying for Sick Leave for the day he/she should also be allowed to apply for other leaves like Casual &amp; Unpaid for different dates on the same day.   Fields I've used:    Start_Date__c (Date type) End_Date__c (Date type) Leave_Type__c (Picklist type)   I want to use a trigger dependent on the Start_Date__c &amp; Leave_Type__c  The Apex Currently in use:  trigger LeaveRecordDuplicateTrigger on New_Casual_Leave__c (before insert) {       for(New_Casual_Leave__c a:Trigger.new)        {         string uid = userinfo.getName();          List&lt;New_Casual_Leave__c&gt; acc=[select Id, CreatedDate, Contact__r.Account.Name,   Start_Date__c, Leave_Type__c from New_Casual_Leave__c where (Contact__r.Account.Name = :uid AND CreatedDate = TODAY)];              if(acc.size()&gt;0)              {                a.adderror('One leave is already applied for the Day For ' + uid);              }        }    }    Please help me out with this.
56738
In Field Service Lightning I have a Trigger on ServiceReport which sends an email with attachment coming from ContentVersion.   This is the Test class I have written.  @isTest  private class testCreateServiceReport{       static testMethod void validateWO() {       WorkOrder wo = new WorkOrder();       wo.subject = 'Testing';       insert wo;       ServiceAppointment sa = new ServiceAppointment();       sa.ParentRecordId = wo.Id;       sa.EarliestStartTime = DateTime.now();       sa.DueDate = DateTime.now();       insert sa;       List&lt;ServiceReportLayout&gt; srl = [Select Id FROM ServiceReportLayout];       ServiceReport sr = new ServiceReport();       sr.ParentId = sa.Id;       sr.Template = srl[0].Id; //Need to check if there is a way to avoid srl[0] notation       insert sr; //If I comment this the text result is pass. When I enable it I get too see the below mentioned error.  }  }   This is the error Methods defined as TestMethod do not support Web service callouts I know that we need to write Test Classes for code that involves web service callouts using setMock() but I dont understand in what way inserting ServiceReport is related to making a callout.  Any help on this will be really helpful.
49131
I'm playing with a trigger exercise, that consists of creating a trigger to create 10 Opportunities whenever a account with more than 100 employees are created. I made the following: trigger AccountTrigger on Account (after insert) {     List&lt;Contact&gt; Contacts = new List&lt;Contact&gt;();     for (Account acct : Trigger.new){                for(integer i = 0; i &lt; 2; i++){             Contact cont    = new Contact();             cont.LastName   = acct.Name+ i;             cont.AccountId  = acct.Id;             Contacts.add(cont);         }         insert Contacts;      if (acct.NumberOfEmployees &gt; 99){         List&lt;Opportunity&gt; Opportunities = new List&lt;Opportunity&gt;();         for(integer i = 0; i &lt; 10; i++){             Opportunity opp = new Opportunity();             opp.Name        = acct.Name + i;             opp.CloseDate   = system.today()+ 30;             opp.StageName   = 'Open';             opp.AccountId   = acct.Id;             Opportunities.add(opp);         }         insert Opportunities;     }                      }  }   And I'm getting the following error: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATES_DETECTED, Use one of these records?:  I didn't created any, or changed the dupe rule of account neither Opportuinities. Can you help me understand what kind of error is this? And how can I change the trigger to workaround it? Thanks in advance!!
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.
27765
I've been trying to leverage custom roll up functionality and found that Database methods is perfoming dml twice. First time it's inserting/updating all records and second time only ones that can be processed. Is it correct? I'm afraid that I'm missing important part in documentation     The optional allOrNone parameter specifies whether the operation allows partial success. If you specify false for this parameter and a record fails, the remainder of the DML operation can still succeed. This method returns a result object that can be used to verify which records succeeded, which failed, and why.   Since I've placed static boolean to check if trigger has been run, I'm loosing data.  If we create test based on the following    @isTest public class Test_accountTrigger {     @isTest     static void Test_saveResult() {         Account[] accts = new List&lt;Account&gt;{             new Account(Name='Account1'),             new Account()};         Database.SaveResult[] srList = Database.insert(accts, false);     } }   Given trigger will be executed twice  trigger accountTrigger on Account (before insert) {     system.debug('accountTrigger.sise: ' + trigger.new.size()); }   Debug  22:25:31.1 (362723328)|USER_DEBUG|[2]|DEBUG|accountTrigger.sise: 2 22:25:31.1 (498071498)|USER_DEBUG|[2]|DEBUG|accountTrigger.sise: 1   I'm trying to update multiple child records within ETL and inside Salesforce update correspondent Parent records with flag allOrNone set to false. If any of those fails I'm adding error to child record. Since I have static boolean check, my first attempt of updating parent records is reverted and second is never happened.
112048
Background  I'm using  to update some picklist values on the fly. (i.e. Every time a record is inserted/updated/deleted in Table A, I'm adding/subtracting picklist values into a MultiselectePicklist in table B).  Since,     An Apex trigger can execute a callout when the callout is invoked within a method defined as asynchronous: that is, defined with the @future keyword.   I implemented a method with the future annotation, and      For Apex code that is executed asynchronously, such as @future methods, Batch Apex jobs, or scheduled Apex jobs, getSessionId returns null.   so, I needed to pass the session Id as a parameter in the method, I implemented something like:  @future (callout=true) public static void addContactPicklistPreference(List&lt;String&gt; preferences, String sessionId){     Schema.DescribeSObjectResult sObjectDescribe = Contact.sObjectType.getDescribe();     String picklistFieldName = 'Preference__c';                    Picklist_MDT.addPicklistValues(sObjectDescribe, picklistFieldName, artists, sessionId); }  public class Picklist_MDT {      public static void addPicklistValues(Schema.DescribeSObjectResult sObjectDescribe, String picklistFieldName, List&lt;String&gt; picklistValueNames, String sessionId) {         MetadataService.MetadataPort service = createService(sessionId);         ...         }       public static MetadataService.MetadataPort createService(String sessionId) {         MetadataService.MetadataPort service = new MetadataService.MetadataPort();         service.SessionHeader = new MetadataService.SessionHeader_element();         service.SessionHeader.sessionId = sessionId;         return service;     } }   And called the addContactPicklistPreference method from trigger context passing it the UserInfo.getSessionId() value.   Problem  This worked just fine in salesforce classic but not in lightning, when it triggers in lightning I'm getting System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: INVALID_SESSION_ID.... Funny thing is that if I put a System.debug(UserInfo.getSessionId()); before calling the addContactPicklistPreference method it prints a valid session Id in both classic and lightning.  I would really appreciate any input about this.
78345
Code  trigger CreatePerson on Contact (before insert) {     RecordType personAccountRecordType =  [SELECT Id FROM RecordType WHERE Name = 'Person Account' and SObjectType = 'Account'];      Map&lt;Contact, Account&gt; accounts = new Map&lt;Contact, Account&gt;();    for(Contact record: Trigger.new) {        if(record.AccountId == null) {            Account newPersonAccount = new Account();            newPersonAccount.FirstName = record.FirstName;            newPersonAccount.LastName = record.LastName;            newPersonAccount.RecordType = personAccountRecordType;             accounts.put(record, newPersonAccount);        }    }     insert accounts.values();     for(Contact record: Trigger.new) {        if(record.AccountId == null) {            record.AccountId = accounts.get(record).Id;        }    } }   Error  Validation Errors While Saving Record(s) There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Can not select a person account".   How can I associate the recently created Person account with the Contact?
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
67965
I have written a class to calculate business hours for Case age in business hours.  The class works great my issue is when trying to write decent test code for the class.  In following testing best practices, I want to create all my own test data and not rely on existing data (seeAllDate=true).  I would assume that in order to test my different scenarios I would need to create and insert new business hours.  Normally, I would use something like the snippet below  BusinessHours newHours = new BusinessHours(     MondayStartTime = Time.newInstance(9, 0, 0, 0),     MondayEndTime = Time.newInstance(17, 0, 0, 0),     TuesdayStartTime = Time.newInstance(9, 0, 0, 0),     TuesdayEndTime = Time.newInstance(17, 0, 0, 0),     WednesdayStartTime = Time.newInstance(9, 0, 0, 0),     WednesdayEndTime = Time.newInstance(17, 0, 0, 0),     ThursdayStartTime = Time.newInstance(9, 0, 0, 0),     ThursdayEndTime = Time.newInstance(17, 0, 0, 0),     FridayStartTime = Time.newInstance(9, 0, 0, 0),     FridayEndTime = Time.newInstance(17, 0, 0, 0),     IsActive = true,     IsDefault = true ); insert newHours;   However, you cannot perform DML on business hours.  Is there a way to do this without having to use seeAllData=true?  I have searched and searched but can;t find much info on using the business hours class in test code.  Any help is much appreciated.
3543
I am trying to create an Apex Trigger that performs a Rollup from a custom object to Contacts.   Here is the error that I am receiving:      Didn't understand relationship 'Assignments__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.   The child relationship name is Assignments.  Below is the code:      trigger RollupActiveAssigmentLevelsToContact on pse__Assignment__c (after insert, after update, after delete) {      set&lt;Id&gt; set_id = new set&lt;Id&gt;();      List&lt;Contact&gt; con_list = new List&lt;Contact&gt;();      if(trigger.isInsert || trigger.isUpdate){         for(pse__Assignment__c myAssignment : trigger.New) {             set_id.add(myAssignment.pse__Resource__c);         }     }     else if(trigger.isDelete){         for(pse__Assignment__c myAssignment : trigger.Old){             set_id.add(myAssignment.pse__Resource__c);         }     }      if(trigger.isAfter &amp;&amp; (trigger.isInsert || trigger.isUpdate || trigger.isDelete)){         con_list = [SELECT id,Total_Levels__c, (SELECT id,name FROM Assignments__r WHERE Active_Assignment__c = TRUE) FROM Contact WHERE id IN :set_id];          for(Contact con : con_list){             if(con.Assignments__r.size()&gt;0)                 con.Total_Levels__c = con.Assignments__r.size();             else                 con.Total_Levels__c = 0;         }         if(!con_list.isEmpty())         update con_list;     } }   Below is a snap of the Child Relationship name:
20599
I am receiving apex errors with the following code:   public with sharing class AddExistingSpecsExt {      public Specifications__c loadedSpec { get; private set; }  public AddExistingSpecsExt() {     String specId = ApexPages.currentPage().getParameters().get('id');     if (String.isBlank(specId)) return;      List&lt;Specifications__c&gt; candidates = [         SELECT Id, Name, Product__c FROM Specifications__c WHERE Id = :specId LIMIT 1     ];     if (!candidates.isEmpty()) loadedSpec = candidates[0]; }     public PageReference associate () {          Specifications__c candidates = new Specifications__c ( Id = Specifications__c.Product__c, Name = Specifications__c.Id);          try {             Database.update(candidates);         } catch (Exception error) {             ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error while associating.' + error.getMessage()));         }          PageReference page = new PageReference('/' + candidates);          return page.setRedirect(true);     }      public PageReference cancel () {         PageReference page = new PageReference('/' + Null);         return page.setRedirect(true);             }  }   Attempting to add records to a related list through a custom button and small vf page.   The Error is Line 16      Invalid initial expression type for field Specifications__c.Id, expecting: Id   Any help?
82462
I need to request leave for one day and for more than one day.  What's the correct way of using the word day?  Which is correct for a single day of leave?        1 day's leave   1 day leave      What about more than one day?        2 day's leave   2 days' leave      Please clarify with explanation.
122089
I try to add an item to my sharepoint list from a custom web part. Is there any mistake in my code?  [WebMethod]         public static string AjouterDemande()         {             SPList ListeDemandeConge = SPContext.Current.Site.RootWeb.Lists["DEMANDE CONGÉ"];             SPListItem ListItem = ListeDemandeConge.Items.Add();             ListItem["CODE"] = code;             ListItem["DEMANDEUR"] = Utilisateur.LoginName;             ListItem["DATE DEMANDE"] = DateTime.Today.Date;             ListItem["DATE FIN"] = EndDateD;             ListItem["DATE DEPART"] = StartDateD;             ListItem["DUREE"] = int.Parse(DayCount);             ListItem["PREMIER RESPONSABLE"] = Employe.FirstSuperior.LoginName;             ListItem["DEUXIEME RESPONSABLE"] = Employe.SecondSuperior.LoginName;             ListItem["PRESENCE PRES"] = Boolean.Parse(FirstRespPresent);             ListItem["SOLDE CONGE"] = Conge.SoldeAnneeConge;             ListItem["MOIS"] = int.Parse(StartDateTab[1]);             ListItem["ANNEE"] = int.Parse(StartDateTab[0]);             ListItem["JOURS APPROUVEES"] = 0;             ListItem.Update();             ListeDemandeConge.Update();             return "true";          }   When I use F10 to process debugging step by step and get to my listitem.update(), it went out without giving any error.
9895
So what I need is a limitation for the user of the funded contracts. So this is what I am trying to implement. I am trying to let the user enter dates within the year 2014, which will bring up how many funded contracts are there for each month. I ONLY want up to the last day of the previous month and the passed months within the year 2014. So for example we are in June, if the user inputs any dates that are before June he can see those months of how many funded contracts are in there - but not any contract from June.   So the user should not be able to see July until we hit August which we can see July from there. Here is my query.  I feel that my where clause for the GetDate is incorrect. Any help will be appreciated             Alter Proc spGetAdminTotalYTD             (@Begin_Date  DATETIME,              @End_Date DATETIME,             @program int=null) As      Begin Declare @year int Set @year = 2014          SELECT  d.name, a.dealer_code, b.last_name, b.city, b.state, b.phone             , COUNT(CASE WHEN  MONTH(c.Funded_date) = 1 THEN 1 ELSE NULL END) January             , COUNT(CASE WHEN  MONTH(c.Funded_date) = 2 THEN 1 ELSE NULL END) Feburary             , COUNT(CASE WHEN  MONTH(c.Funded_date) = 3 THEN 1 ELSE NULL END) March             , COUNT(CASE WHEN  MONTH(c.Funded_date) = 4 THEN 1 ELSE NULL END) April             , COUNT(CASE WHEN  MONTH(c.Funded_date) = 5 THEN 1 ELSE NULL END) May             , COUNT(CASE WHEN  MONTH(c.Funded_date) = 6 THEN 1 ELSE NULL END) June             , COUNT(CASE WHEN  MONTH(c.Funded_date) = 7 THEN 1 ELSE NULL END) July             , COUNT(CASE WHEN  MONTH(c.Funded_date) = 8 THEN 1 ELSE NULL END) August             , COUNT(CASE WHEN  MONTH(c.Funded_date) = 9 THEN 1 ELSE NULL END) September             , COUNT(CASE WHEN  MONTH(c.Funded_date) = 10 THEN 1 ELSE NULL END) October             , COUNT(CASE WHEN  MONTH(c.Funded_date) = 11 THEN 1 ELSE NULL END) November             , COUNT(CASE WHEN  MONTH(c.Funded_date) = 12 THEN 1 ELSE NULL END) December,             COUNT(1) AS YTD         FROM tdealer a JOIN tContact b ON a.contact_id = b.contact_id               JOIN tContract  c ON a.dealer_id = c.dealer_id JOIN tCompany d               ON  c.company_id = d.company_id         WHERE YEAR(c.Funded_date) = @Year              AND c.Funded_date &gt;= DATEADD(MONTH, DATEDIFF(MONTH, 0,GETDATE())-4,0)              AND c.Funded_date &lt;  DATEADD(MONTH, DATEDIFF(MONTH,-1,GETDATE())-4,0)              AND c.program_id = @program              AND c.funded_date Between @Begin_Date And @End_Date              GROUP BY     d.name,     a.dealer_code,     b.last_name,     b.city,     b.state,     b.phone     END
94031
I have a query in a before-update trigger that looks like following:  [SELECT Id,(SELECT Id,Active_opp__c              FROM Opportunities              ORDER BY Days_from_Last_Stage__c ASC)   FROM Account WHERE Id IN: conAccMap.values()]   I have checked this in query plan and it looks like :    Is there a chance that the inner query will cause selective query error since I dont have a WHERE Clause on an indexed field in the inner query?
7576
I have a lookup to a custom object called Project on my Opportunity object. I am trying to write a trigger that updates an Active, Awarded, and Title on the Project object whenever the Active, Awarded, or Title field is updated on Opportunity based some on more logic that isn't in my code below. This is my first trigger and needing a little help due to a NullPointerException where I try to set Project__r.Active__c = true. Any thoughts?      trigger ProjectFieldsTrigger on Opportunity (before insert, before update) {       //List&lt;Opportunity&gt; opp = [SELECT Name, Active__c, Funded__c, Title__c, Project__r.Name, Project__r.Active__c, Project__r.Awarded__c      //  FROM Opportunity WHERE Id IN :Trigger.New];      for(Opportunity o: Trigger.New){          if(o.Project__c != null){              if(o.Active__c == 'Y'){                 o.Project__r.Active__c = true;             }      }  }
108596
I have a custom object that I want to set a unique key based on on lookup values. When I tried to create a workflow update I was blowing past the size limit so I developed it into a trigger and it seems to be working as intended.   I thought since I am already developing a field update trigger, I might as well add on a default name method so everything is contained into one file as opposed to having workflow and triggers updating the record.   When I introduced this method it returns "null null".   public static void setRecordName(List&lt;Responsible_Party__c&gt; newList) {     for(Responsible_Party__c r : newList)     {         r.Name = r.Practice__r.Name + ' ' + r.User__r.Name;     } }   Where practice is a lookup to another custom object and user is a lookup to the user object.   If I change the values to just use the field:  public static void setRecordName(List&lt;Responsible_Party__c&gt; newList) {     for(Responsible_Party__c r : newList)     {         r.Name = r.Practice__c + ' ' + r.User__c;     } }   I get "a1Gg00000049v9xEAA 005A0000006ykwnIAA". How can I get the names to display and not null?