-
ChatterFeed
-
0Best Answers
-
0Likes Received
-
0Likes Given
-
18Questions
-
14Replies
system limitexception too many callouts: 101 - HOW TO FIX
I am attempting to fix my class that is making API calls to an external system. I am thinking that nextUrl is returning more than 100 nextUrl's which is making the code call out more than 100 times. I basically want to be able to call nextUrl until there is no longer a nextUrl returned from the call. What would be the best way to solve this issue ??
Here is the code for context. (I have removed the original URL and header for security reasons)
Here is the code for context. (I have removed the original URL and header for security reasons)
public class Zenefits_Time_Off implements Schedulable, Database.AllowsCallouts { public void execute(SchedulableContext SC) { makeCallout(); } @future(callout = true) public static void makeCallout() { string url = 'xxxxxxxxxx'; do { url = makeHttpCall(url); } while(url != null); processData(); } static map<String,Id> ProjectList = new Map<string,Id>(); static List<Object> vacationRequests = new List<Object>(); static { for (pse__Proj__c proj : [SELECT Id, Name FROM pse__Proj__c WHERE Name Like 'PTO%'LIMIT 1]) { ProjectList.put('pto',proj.Id); } } public static String makeHttpCall(String url) { string nextUrl; Http http = new Http(); HttpRequest request = new HttpRequest(); request.setHeader('Authorization', 'xxxxxxxxxxxxx'); request.setEndpoint(url); request.setMethod('GET'); HttpResponse response = http.send(request); // If the request is successful, parse the JSON response. if (response.getStatusCode() == 200) { // Deserializes the JSON string into collections of posts. Map<String, Object> wrapper = (Map<String, Object>) JSON.deserializeUntyped(response.getBody()); if(wrapper != null) { Map<String, Object> wrapper2 = (Map<String, Object>) wrapper.get('data'); if (wrapper2 != null) { nextUrl = (String) wrapper2.get('next_url'); vacationRequests.addAll((List<Object>)wrapper2.get('data')); } } } return nextUrl; } public static void processData() { List<Time_Off_Request__c> torToUpdate = new List<Time_Off_Request__c> (); Map<String,map<String, Object>> ptoMap = new Map<String,map<String, Object>>(); set<string> employeeIdSet = new set<string>(); for (Object vacationRequestWrapper : vacationRequests) { Map<String, Object> vacationRequest = (Map<String, Object>) vacationRequestWrapper; if (vacationRequest.get('status') == 'approved') { Map<String, Object> wrapper3 = (Map<String, Object>) vacationRequest.get('creator'); Map<String,Object> empValues = new Map<String,Object>(); string ptoUrl = (String) wrapper3.get('url'); string ptoId = (string)vacationRequest.get('id'); string employeeId = ptoUrl.substring(ptoUrl.length() - 7, ptoUrl.length() - 0); string hours = (String)vacationRequest.get('hours'); decimal hoursDec = decimal.valueOf(hours); string status = (String)vacationRequest.get('status'); empValues.put('startDate',vacationRequest.get('start_date')); empValues.put('endDate',vacationRequest.get('end_date')); empValues.put('ptoId',vacationRequest.get('id')); empValues.put('hours', hoursDec); empValues.put('empId', employeeId); ptoMap.put(ptoId, empvalues); employeeIdSet.add(employeeId); } } Map<String, Object> tempEmpValues = new Map<String, Object>(); Map<String,Object> contactVal = new Map<String,Object>(); map<String,Id> conZenIdMap = new map<String,Id>(); for (Contact con : [SELECT FirstName, LastName, Zenefits_ID__c FROM Contact WHERE Zenefits_ID__c IN : employeeIdSet]) { conZenIdMap.put(con.Zenefits_ID__c,con.Id); } for(Time_Off_Request__c tor1 : [SELECT ID, Zenefits_ID__c FROM Time_Off_Request__c WHERE Zenefits_ID__c IN : ptoMap.keySet()]) { ptoMap.remove(tor1.Zenefits_ID__c); //remove existing Time Off Requests } for(String zId: ptoMap.keyset()) { map<String,Object> currMap = ptoMap.get(zId); map<String, Integer> hours = new Map<String, Integer>(); Time_Off_Request__c tor = new Time_Off_Request__c(); if(conZenIdMap.get((string)currMap.get('empId')) != null) { tor.Employee__c =conZenIdMap.get((string)currMap.get('empId')); tor.Project__c = (string)ProjectList.get('pto'); tor.First_Day_Off__c = date.valueof((string)currMap.get('startDate')); tor.Last_Day_Off__c = date.valueof((string)currMap.get('endDate')); tor.Status__c = 'Saved'; tor.Zenefits_ID__c = zId; tor.hours_off__c = (Decimal)currMap.get('hours'); torToUpdate.add(TOR); } } insert torToUpdate; } }
- Kris Webster
- November 16, 2020
- Like
- 0
Map Comparison Help !
I am attempting to construct a class that will create Timecards for users automatically in my system.
I know this is a basic question but I am just stuck...
Here is the code
at the very bottom how can I pull out the PTOmap pto.employee__c so that I can use it to compare it to the tch.pse__Resource__c value?
My logic is that if there are any PTO requests in the PTO map where the pto.employee__c = tch.pse__Resource__c then I want to populate a list with the associated PTO start dates associated with the specific tch.pse__Resource__c?
Any help would be GREATLY appreciated
I know this is a basic question but I am just stuck...
Here is the code
global class Monthly_TC_Creator implements Database.Batchable<sObject> { //query the list of holidays from the holiday object private pse__Proj__c proj = new pse__Proj__c(); public Monthly_TC_Creator() { } global Database.queryLocator start(Database.BatchableContext ctx) { //Query all the assignments that are active and Billable in the system Date d = system.today(); String str = 'SELECT Id, pse__Start_Date__c, pse__End_Date__c, pse__Resource__c, Start_of_The_Week__c, End_of_Month_Calculator__c, Today__c, pse__Project__c, pse__Is_Billable__c FROM pse__Assignment__c WHERE pse__End_date__c >: d'; return Database.getQueryLocator(str); } global void execute(Database.BatchableContext ctx, List<pse__Assignment__c> TCs_to_create) { List<Date> HolidayList = new List<Date>(); List<pse__HolidayObj__c> tempHolidayList = [SELECT pse__Date__c from pse__HolidayObj__c]; for (pse__HolidayObj__c holiday : tempHolidayList) { HolidayList.add(holiday.pse__Date__c); system.debug('holiday ' + HolidayList); } //Map to store all the PTO requests in. We will only store PTO requests for the current month Map<String,map<String, Object>> ptoMap = new Map<String,map<String, Object>>(); Map<String,Object> PTOValues = new Map<String,Object>(); List<Time_Off_Request__c> tempPTOList = [SELECT Employee__c, Total_Days_Off__c , First_Day_Off__c, Last_Day_Off__c FROM Time_Off_Request__c]; for(Time_Off_Request__c PTO : tempPTOList) { PTOValues.put('PTO ID', PTO.id); PTOValues.put('PTO First Day Off', PTO.First_Day_Off__c); PTOValues.put('PTO Last Day Off', PTO.Last_Day_Off__c); PTOValues.put('employee', PTO.Employee__c); PTOValues.put('NumberOfDays', PTO.Total_Days_Off__c); ptoMap.put(pto.employee__c,PTOValues); system.debug('ptoValues ' + PTOValues); } List<pse__Timecard_Header__c> timeCardList = new List<pse__Timecard_Header__c> (); list<Date> firstDayOff = new List<Date>(); for (pse__Assignment__c ass : TCs_to_create) { map<string, datetime> endDateList = new map<string, datetime>(); ///////////////////////////////////////////// // Get the correct hours for the correct Days DateTime startDate = ass.Start_of_The_Week__c ; system.debug('Original Start Date ' + startDate); if(ass.pse__End_Date__c > ass.End_of_Month_Calculator__c){ DateTime endDate = ass.End_of_Month_Calculator__c; endDateList.put('endDate', endDate); system.debug('endDate1 ' + endDate); } else if (ass.pse__End_Date__c < ass.End_of_Month_Calculator__c){ DateTime endDate = ass.pse__End_Date__c; endDateList.put('endDate', endDate); system.debug('endDate2 ' + endDate); } Date startDateTC = ass.Start_of_The_Week__c; map<String, Integer> hours = new Map<String, Integer>(); Map<String, DateTime> secondTC = new Map<String, DateTime>(); list<string> Days = new List<String>(); list<date> PtoStartDate = new list<date>(); pse__Timecard_Header__c tch = new pse__Timecard_Header__c(); tch.CurrencyIsoCode = 'USD'; tch.pse__Project__c = ass.pse__Project__c; tch.pse__Assignment__c = ass.id; tch.pse__Resource__c = ass.pse__Resource__c; tch.pse__Start_Date__c = startDateTC; tch.pse__End_Date__c = startDateTC.addDays(6); tch.pse__Billable__c = true; tch.pse__Time_Credited__c = true; tch.pse__Time_Excluded__c = false; tch.pse__Bill_Rate__c = null; tch.pse__Cost_Rate_Amount__c = null; tch.pse__Cost_Rate_Currency_Code__c = null; tch.pse__Status__c = 'Saved'; tch.pse__Submitted__c = False; tch.pse__Approved__c = False; tch.pse__Include_In_Financials__c = False; //now we search the current resource for PTO and take those days out of the TC creation
at the very bottom how can I pull out the PTOmap pto.employee__c so that I can use it to compare it to the tch.pse__Resource__c value?
My logic is that if there are any PTO requests in the PTO map where the pto.employee__c = tch.pse__Resource__c then I want to populate a list with the associated PTO start dates associated with the specific tch.pse__Resource__c?
Any help would be GREATLY appreciated
- Kris Webster
- January 06, 2020
- Like
- 0
Scheduling a API Callout HELP
Good afternoon all ! I am attempting to schedule an API callout using the Database.Batchable method.
I have all the code written and have attempted to schedule the class via the Salesforce Scheduler interface, however when the code was excecuted nothing happened to the records the code is supposed to update. ** When I run the class via ANONYMOUS APEX it works perfectly though... is there a better way to schedule this class ?
Here is the API Callout class
I have all the code written and have attempted to schedule the class via the Salesforce Scheduler interface, however when the code was excecuted nothing happened to the records the code is supposed to update. ** When I run the class via ANONYMOUS APEX it works perfectly though... is there a better way to schedule this class ?
Here is the API Callout class
global class ZenefitsEmployees implements Database.Batchable<sObject> { public String query = 'Select ID, Name from Contact'; global Database.QueryLocator start(Database.BatchableContext ctx) { return Database.getQueryLocator(query); } global void execute (Database.BatchableContext ctx, List<Contact> records) { string url = 'REMOVED FOR SECURTY PURPOSES'; Integer int1 = 0; Http http = new Http(); HttpRequest request = new HttpRequest(); request.setHeader('Authorization', 'Bearer REMOVED FOR SECURITY PURPOSES'); request.setEndpoint(url); request.setMethod('GET'); HttpResponse response = http.send(request); // If the request is successful, parse the JSON response. if (response.getStatusCode() == 200) { // Deserializes the JSON string into collections of posts. Map<String,Object> wrapper = (Map<String,Object>) JSON.deserializeUntyped(response.getBody()); if (wrapper.containsKey('data')) { Map<String, Object> wrapper2 = (Map<String,Object>) wrapper.get('data'); if(wrapper2.containsKey('data')) { List<Object> people = (List<Object>)wrapper2.get('data'); for (Object peopleWrapper : people) { Map<String,Object> Employees = (Map<String,Object>) peopleWrapper; if(Employees.containsKey('last_name')){ String ZenefitsLastName = (String) Employees.get('last_name'); String ZenefitsFirstName = (String) Employees.get('first_name'); String ZenefitseEmployeeId = (String) Employees.get('id'); String ZenefitsEmail = (String) Employees.get('work_email'); List<Contact> contactList = [SELECT Id, FirstName, LastName, Zenefits_ID__c, Email FROM Contact WHERE Email = :ZenefitsEmail LIMIT 200]; List<Contact> contactsToUpdate = new List<Contact>(); for(Contact con : contactList){ con.Zenefits_Id__c = ZenefitseEmployeeId; contactsToUpdate.add(con); } update contactsToUpdate; system.debug('Employees ' + Employees); system.debug('last name ' + ZenefitsLastName); system.debug('Employee id ' + ZenefitseEmployeeId); system.debug('first name ' + ZenefitsFirstName); system.debug('Contact list ' + contactList); system.debug('TEST ' + contactsToUpdate); } } } return ; } return ; } return ; } global void finish(Database.BatchableContext ctx) { AsyncApexJob a = [SELECT Id, Status, ExtendedStatus, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id = :ctx.getJobId()]; // Send an email to the Apex job's submitter notifying of job completion. Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {a.CreatedBy.Email}; mail.setToAddresses(toAddresses); mail.setSubject('Apex Sharing Recalculation ' + a.Status); mail.setPlainTextBody ('The batch Apex job processed ' + a.TotalJobItems + ' batches with '+ a.NumberOfErrors + ' failures. The error is related to ' + a.ExtendedStatus); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } }And then I have a second scheduleable class that calls this class and theoretically executes the code..
global class GetPeople implements Schedulable { global void execute(SchedulableContext ctx) { database.executeBatch(new ZenefitsEmployees(),200); } }ANY HELP WOULD BE GREAT!!
- Kris Webster
- October 10, 2019
- Like
- 0
Schedule REST API Callout HELP
Good afternoon,
I have a API call class that is working as I need it to, however I am not trying to get the class to execute every night at 2 AM. I am trying to implement a schedulable class to call the API class and make it execute every night, but am a little unsure how to do this..
Here is my REST API class
For anyone that has implemented a way to have an API call excecute every night on a daily basis please share your wisdome with me !!
Thanks in advance !!
I have a API call class that is working as I need it to, however I am not trying to get the class to execute every night at 2 AM. I am trying to implement a schedulable class to call the API class and make it execute every night, but am a little unsure how to do this..
Here is my REST API class
string url = *****; Integer int1 = 0; String myProcedure1() { Http http = new Http(); HttpRequest request = new HttpRequest(); request.setHeader('Authorization', 'Bearer ****); request.setEndpoint(url); request.setMethod('GET'); HttpResponse response = http.send(request); // If the request is successful, parse the JSON response. if (response.getStatusCode() == 200) { // Deserializes the JSON string into collections of posts. Map<String,Object> wrapper = (Map<String,Object>) JSON.deserializeUntyped(response.getBody()); if (wrapper.containsKey('data')) { Map<String, Object> wrapper2 = (Map<String,Object>) wrapper.get('data'); if(wrapper2.containsKey('data')) { List<Object> people = (List<Object>)wrapper2.get('data'); for (Object peopleWrapper : people) { Map<String,Object> Employees = (Map<String,Object>) peopleWrapper; if(Employees.containsKey('last_name')){ String ZenefitsLastName = (String) Employees.get('last_name'); String ZenefitsFirstName = (String) Employees.get('first_name'); String ZenefitseEmployeeId = (String) Employees.get('id'); String ZenefitsEmail = (String) Employees.get('work_email'); List<Contact> contactList = [SELECT Id, FirstName, LastName, Zenefits_ID__c, Email FROM Contact WHERE Email = :ZenefitsEmail LIMIT 200]; List<Contact> contactsToUpdate = new List<Contact>(); for(Contact con : contactList){ con.Zenefits_Id__c = ZenefitseEmployeeId; contactsToUpdate.add(con); } update contactsToUpdate; //we now need to find all contacts in SF that match the contacts in Employees //once we have matches we need to synce each ID system.debug('Employees ' + Employees); system.debug('last name ' + ZenefitsLastName); system.debug('Employee id ' + ZenefitseEmployeeId); system.debug('first name ' + ZenefitsFirstName); system.debug('Contact list ' + contactList); system.debug('TEST ' + contactsToUpdate); } } } return null; } return null; } return null; } void myProcedure2() { while (url != null) { System.debug('BEFORE URL: ' + url); url = myProcedure1(); System.debug('AFTER URL: ' + url); } } myProcedure2();I have gone ahead and taken out the URL and the Bearer headers for privacy purposes, but all else is there.
For anyone that has implemented a way to have an API call excecute every night on a daily basis please share your wisdome with me !!
Thanks in advance !!
- Kris Webster
- October 09, 2019
- Like
- 0
API Query HELP
I am trying to query salesforce data based on information that I am pulling from our HR system via a REST API callout to the HR system.
Basically I am tring to find all contacts in my Salesforce org where the first name = the first name in the API Call. I know that first name is not specific enough, but I am starting here and once I can get records to match I will use a more unique identifier.
Here is my code. I NEED HELP WITH LINE 28! I have left out authorization lines for privacy sake.
Basically I am tring to find all contacts in my Salesforce org where the first name = the first name in the API Call. I know that first name is not specific enough, but I am starting here and once I can get records to match I will use a more unique identifier.
Here is my code. I NEED HELP WITH LINE 28! I have left out authorization lines for privacy sake.
request.setMethod('GET'); HttpResponse response = http.send(request); // If the request is successful, parse the JSON response. if (response.getStatusCode() == 200) { // Deserializes the JSON string into collections of posts. Map<String,Object> wrapper = (Map<String,Object>) JSON.deserializeUntyped(response.getBody()); if (wrapper.containsKey('data')) { Map<String, Object> wrapper2 = (Map<String,Object>) wrapper.get('data'); if(wrapper2.containsKey('data')) { List<Object> people = (List<Object>)wrapper2.get('data'); for (Object peopleWrapper : people) { Map<String,Object> Employees = (Map<String,Object>) peopleWrapper; if(Employees.containsKey('last_name')){ String ZenefitsLastName = (String) Employees.get('last_name'); String ZenefitsFirstName = (String) Employees.get('first_name'); String ZenefitseEmployeeId = (String) Employees.get('id'); List<Contact> contactList = [SELECT Id, FirstName, LastName FROM Contact WHERE FirstName = Employees.get('first_name') LIMIT 200]; //we now need to find all contacts in SF that match the contacts in Employees //once we have matches we need to synce each ID system.debug('Employees ' + Employees); system.debug('last name ' + ZenefitsLastName); system.debug('Employee id ' + ZenefitseEmployeeId); system.debug('first name ' + ZenefitsFirstName); system.debug('Contact list ' + contactList); } } } return null; } return null; } return null; }
- Kris Webster
- October 08, 2019
- Like
- 0
Why Isn't My Test Class Testing my REAL Class
I have a standard cladd, a schedulable class, and a test class. When I run my test on the test class the schedulable class passes 100% coverage, however the test calss still sits at 0% coverage, which tells me that the test class may not be testing the standard class at all?? I NEED HELP PLEASE haha.
Here is the standard class
Here is the test class...
and here is the schedulable class..
Here is the standard class
global class TCApprovalCompliance implements Database.Batchable<sObject> { global Database.queryLocator start(Database.BatchableContext ctx ) { String str = 'SELECT Id, pse__Submitted__c, pse__Start_Date__c, pse__Approved__c FROM pse__Timecard_Header__c WHERE pse__Submitted__c = TRUE'; return Database.getQueryLocator(str); } global void execute(Database.BatchableContext ctx, List<pse__Timecard_Header__c> nonApprovedTCs) { List<pse__Timecard_Header__c> TCList = new List<pse__Timecard_Header__c>(); for(pse__Timecard_Header__c tcObj : nonApprovedTCs){ tcObj.Approval_Compliance__c = true; TCList.add(tcObj); } update TCList; } global void finish(Database.BatchableContext ctx) { AsyncApexJob a = [SELECT Id, Status, ExtendedStatus, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id = :ctx.getJobId()]; // Send an email to the Apex job's submitter notifying of job completion. Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {a.CreatedBy.Email}; mail.setToAddresses(toAddresses); mail.setSubject('Apex Sharing Recalculation ' + a.Status); mail.setPlainTextBody ('The batch Apex job processed ' + a.TotalJobItems + ' batches with '+ a.NumberOfErrors + ' failures. The error is related to ' + a.ExtendedStatus); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } }
Here is the test class...
@isTest public class TCApprovalCompliance_TEST { static testMethod void testTCApprovalCompliance() { //loadSettings(); disableTriggerHandlers(true); TestDataFactory.initPermissionControls(); TestDataFactory.timecardHeaders = TestDataFactory.createTimecardHeaders(1, false); TestDataFactory.timecardHeaders[0].pse__Start_Date__c = date.parse('09/01/2019'); TestDataFactory.timecardHeaders[0].pse__End_Date__c = date.parse('09/07/2019'); TestDataFactory.TimecardHeaders[0].pse__Status__c = 'Submitted'; TestDataFactory.TimecardHeaders[0].pse__Submitted__c = TRUE; TestDataFactory.TimecardHeaders[0].pse__Approved__c = FALSE; Test.startTest(); insert TestDataFactory.timecardHeaders; system.debug('Cb is checked?? ' + testdatafactory.timecardHeaders[0].Approval_Compliance__c); system.debug('Start date is... ' + testdatafactory.timecardHeaders[0].pse__Start_Date__c); system.debug('submitted is... ' + testdatafactory.timecardHeaders[0].pse__Submitted__c); system.debug('approved is... ' + testdatafactory.timecardHeaders[0].pse__Approved__c); system.debug('The Id is... ' + testdatafactory.timecardHeaders[0].Id); Test.stopTest(); TCApprovalCompliance_Schedulable TC1 = new TCApprovalCompliance_Schedulable(); String sch = '0 0 23 * * ?'; system.schedule('Test Update Contacts Check', sch, TC1); } private static void loadSettings() { TestDataFactory.loadAllConfigGroupsOptionsValues(); TestDataFactory.updateAsmTriggerSettings(TestDataFactory.getDefaultDisableAsmTriggerSettings()); TestDataFactory.createSRPIntegrationSettings(true, true); TestDataFactory.createProjectTriggerSettings(true); TestDataFactory.createTimecardComplianceSettings(true); TestDataFactory.createCommonSettingsSettings(true); } private static void disableTriggerHandlers(boolean disableTimecardTriggers) { TriggerHandlerBase.disableAllTriggerHandlers(Account.sObjectType); TriggerHandlerBase.disableAllTriggerHandlers(Contact.sObjectType); TriggerHandlerBase.disableAllTriggerHandlers(pse__Region__c.sObjectType); TriggerHandlerBase.disableAllTriggerHandlers(pse__Practice__c.sObjectType); TriggerHandlerBase.disableAllTriggerHandlers(pse__Grp__c.sObjectType); TriggerHandlerBase.disableAllTriggerHandlers(pse__Proj__c.sObjectType); TriggerHandlerBase.disableAllTriggerHandlers(pse__Assignment__c.sObjectType); if (disableTimecardTriggers == true) { TriggerHandlerBase.disableAllTriggerHandlers(pse__Timecard_Header__c.sObjectType); TriggerHandlerBase.disableAllTriggerHandlers(pse__Timecard__c.sObjectType); } } }
and here is the schedulable class..
global class TCApprovalCompliance_Schedulable implements Schedulable { global void execute(SchedulableContext ctx) { database.executeBatch(new TCApprovalCompliance(),200); } }
- Kris Webster
- September 05, 2019
- Like
- 0
String Query Syntax HELP
Hey guys I am needing some help with the way I need to format this string query so it will look up the records I need it to.
Basically I need the query to look up contacts that are on a billable assignment that also have Is Resource = TRUE, Is Resource Active = TRUE, and Exclude From Time Calculations = FALSE, and the Work Calandar = weekStartDay.
I am able to perform this string in the Query editor and find the results I am looking for, but am unsure of the exact syntax that is needed in Apex.
Here is what I have so far...
I am then hoping to find a list of contacts that aer found within the first string, by using the contact ID and comparing it to pse__Resource__c, which is a lookup field to contacts on the Assignment object.
Any help would be GREATLY apprecaited!!
Basically I need the query to look up contacts that are on a billable assignment that also have Is Resource = TRUE, Is Resource Active = TRUE, and Exclude From Time Calculations = FALSE, and the Work Calandar = weekStartDay.
I am able to perform this string in the Query editor and find the results I am looking for, but am unsure of the exact syntax that is needed in Apex.
Here is what I have so far...
string assignments = 'SELECT Id, pse__End_Date__c, pse__Resource__c, pse__Is_Billable__c, Today__c FROM pse__Assignment__c WHERE pse__Is_Billable__c = True AND pse__End_Date__c > TODAY'; string queryString = 'SELECT Id, ' + ' Name ' + ' FROM Contact ' + ' WHERE Id Like: assignments.pse__Resource__c AND' + ' pse__Is_Resource__c = true AND ' + ' pse__Is_Resource_Active__c = true AND ' + ' pse__Exclude_From_Missing_Timecards__c = false AND ' + ' pse__Work_Calendar__r.pse__Week_Start_Day__c = \'' + weekStartDay + '\' ';In the first string I am finding all the assignments that are bilalble, and have an end date greater than TODAY.
I am then hoping to find a list of contacts that aer found within the first string, by using the contact ID and comparing it to pse__Resource__c, which is a lookup field to contacts on the Assignment object.
Any help would be GREATLY apprecaited!!
- Kris Webster
- September 04, 2019
- Like
- 0
Populate Lookup Field Upon Record Creation
I am trying to create a trigger that will populate a lookup field on a custom object called Levvel Forecat.
The basic criteria here is that when a new Levvel Forecast record is created with a specific record type I need to update Assignment__c (Lookup field to assignment (pse__assignment__c) object) with the current active assignment that the contact (lookup field to Contact record) on the levvel Forecast record is on.
So what I have done is trying to perform a select statement to store the contact id (Employee__c) on the Levvel Forecast record so we can use that in the second Select statement as a comparison.
I have then created a second SELECT statement to select the pse__Assignment__c WHERE the Contact Id on the assignment is EQUAL to the contact Id on the levvel Forecast.
Then I have a simple IF statement, and if it passed I am trying to insert that assignment ID into the Assignment__c field on the Levvel Forecast record.
CURENTLY in my test class I am getting the error saying that there is “Too many SOQL queries 101”
Any help would be greatly appreciated!
I have this methos inserted within my LevvelForecastTriggerHandler so i am sorry if it doesnt look like a conventional Trigger..
**** The method that is running all this is the "loadAssignment" method, and is also looking at the BULKBEFORE after the line that reads "if(trigger.isInsert)"....
The basic criteria here is that when a new Levvel Forecast record is created with a specific record type I need to update Assignment__c (Lookup field to assignment (pse__assignment__c) object) with the current active assignment that the contact (lookup field to Contact record) on the levvel Forecast record is on.
So what I have done is trying to perform a select statement to store the contact id (Employee__c) on the Levvel Forecast record so we can use that in the second Select statement as a comparison.
I have then created a second SELECT statement to select the pse__Assignment__c WHERE the Contact Id on the assignment is EQUAL to the contact Id on the levvel Forecast.
Then I have a simple IF statement, and if it passed I am trying to insert that assignment ID into the Assignment__c field on the Levvel Forecast record.
CURENTLY in my test class I am getting the error saying that there is “Too many SOQL queries 101”
Any help would be greatly appreciated!
I have this methos inserted within my LevvelForecastTriggerHandler so i am sorry if it doesnt look like a conventional Trigger..
**** The method that is running all this is the "loadAssignment" method, and is also looking at the BULKBEFORE after the line that reads "if(trigger.isInsert)"....
/************************************************************************************************************************ // Name LevvelForecastTriggerHandler // Description Standard trigger handler for LevvelForecastTrigger // INITIAL 2019-Aug-16 KWEBB Initial version ************************************************************************************************************************/ public without sharing class LevvelForecastTriggerHandler extends TriggerHandlerBase { //List for querying forecast periods for DELETE private List<Forecast_Periods__c> forecastPeriodList = new List<Forecast_Periods__c>(); //list for storing all active assignemnts that are realted to the new forecast creations private List<pse__Assignment__c> assignmentList = new List<pse__Assignment__c>(); /************************************************************************************************************ // Name bulkBefore // Description Standard implementation of the TriggerHandler.bulkBefore() interface method. *************************************************************************************************************/ public override void bulkBefore() { if (trigger.isDelete) { //store parent Levvel Forecast records that are about to be deleted list<Id> forecastIds = new list<Id>(); for(SObject so :trigger.old) { Levvel_Forecast__c forecast = (Levvel_Forecast__c)so; forecastIds.add(forecast.id); } //Now we need to query all child Forecast Period records related to the Levvel Forecast we are about to delete forecastPeriodList = [SELECT Id, Levvel_Forecast__c FROM Forecast_Periods__c WHERE Levvel_Forecast__c IN: forecastIds]; system.debug('List of Forecast Periods ' + forecastPeriodList); } if(trigger.isInsert) { //store the LevvelForecast record for update list<Id> forecastsToUpdate = new List<Id>(); for(SObject so :trigger.new) { Levvel_Forecast__c newForecast = (Levvel_Forecast__c)so; if(newForecast.RecordTypeId == '0121N000000U6GYQA0' ) { forecastsToUpdate.add(newForecast.employee__c); } } //Now we need to query all the assignments assignmentList = [SELECT id, pse__Resource__c FROM pse__Assignment__c WHERE pse__Resource__c IN: forecastsToUpdate]; } } /************************************************************************************************************ // Name beforeInsert // Description Standard implementation of the TriggerHandler.beforeInsert() interface method. *************************************************************************************************************/ public override void beforeInsert (SObject so) { Levvel_Forecast__c newForecast = (Levvel_Forecast__c)so; loadAssignment(newForecast); } /************************************************************************************************************ // Name beforeDelete // Description Standard implementation of the TriggerHandler.beforeInsert() interface method. *************************************************************************************************************/ public override void beforeDelete(SObject so) { Levvel_Forecast__c oldForecast = (Levvel_Forecast__c)so; deleteForecastPeriods(oldForecast); } /************************************************************************************************************ // Name loadAssignment // Description Helper method to validate resource requests on an opportunity *************************************************************************************************************/ private void loadAssignment (Levvel_Forecast__c newForecast) { for (pse__Assignment__c ass :assignmentList ) if(ass.pse__End_Date__c > newForecast.Today__c && ass.pse__Is_Billable__c == TRUE) { newForecast.employee__c = ass.pse__resource__c; } } /************************************************************************************************************ // Name deleteForecastPeriods // Description Helper method to validate resource requests on an opportunity *************************************************************************************************************/ private void deleteForecastPeriods (Levvel_Forecast__c oldForecast) { //Now we delete delete forecastPeriodList; } }
- Kris Webster
- August 20, 2019
- Like
- 0
Schedule Apex class to query Assignments and add Assignment to Contact record.
I am trying to create an Apex class that will run every night and update a field on Contact based on specidic criteria.
Basically what I need to happen is for the system to query all assignemnts (pse__assignment__c) in the system with an end date (pse__End_Date__c) greater than TODAY (today__c)
I then need to add that assignemnt to a custom field I have created on Contact if the assignment passes the criteria. If there are no assignments for the specific contact then I need the assignment field to be NULL.
There is a lookup relationship between Assignemtn and Contact. In my code I think I am querying the assignments correctly but I am strugling with figuring out how to then associate that specific assignment with the correct contact. I am also struggling with how to make this Class a schedulable class that I am able to schedule to run every night.
Here is my code so far.
Any help would be GREATLY APPRECIATED
Basically what I need to happen is for the system to query all assignemnts (pse__assignment__c) in the system with an end date (pse__End_Date__c) greater than TODAY (today__c)
I then need to add that assignemnt to a custom field I have created on Contact if the assignment passes the criteria. If there are no assignments for the specific contact then I need the assignment field to be NULL.
There is a lookup relationship between Assignemtn and Contact. In my code I think I am querying the assignments correctly but I am strugling with figuring out how to then associate that specific assignment with the correct contact. I am also struggling with how to make this Class a schedulable class that I am able to schedule to run every night.
Here is my code so far.
Any help would be GREATLY APPRECIATED
public class AssignmentToContact implements Database.Batchable<sObject> { global Database.queryLocator start(Database.BatchableContext ctx ) { list<pse__Assignment__c> aid=New list<pse__Assignment__c>(); list<Contact> updatecontact = new list<Contact>(); for(pse__Assignment__c ass: Trigger.new){ if(ass.pse__End_Date__c >= today__c && ass.pse__Is_Billable__c = TRUE){ aid.add(ass.id); } list<Contact> contactlist=[SELECT Id,Assignment__c FROM Contact WHERE id = :aid]; for(Contact con: contactlist){ con.Assignment__c=ass.Id; updatecontact.add(con); } } update updatecontact; } } //IF THE list is empty then the field on CONTACT should be NULL
- Kris Webster
- July 31, 2019
- Like
- 0
AfterInsert Error PLEASE HELP
I am attempting to upate a field on the Opportunity object with the project that gets created (that is associated to the opportunity)
So basically the way things work is that when an opportunity is set to closed won a project gets created with a lookup relationship back to the opportunity. There is a field on the Project that automatically gets filled with the opportunity name, however the field on the Opportunity that is supposed to get filled with the project name is not being filled when the project is created.
I have attempted to write some code to uopdate that field after the project is inserted. My logic seems correct however the field (Pse__Primary__Project__C) is not being uopdated with the project name.
Here is the code..
ANy help would be MUCH appreciated!! THANKS IN ADVANCE!
So basically the way things work is that when an opportunity is set to closed won a project gets created with a lookup relationship back to the opportunity. There is a field on the Project that automatically gets filled with the opportunity name, however the field on the Opportunity that is supposed to get filled with the project name is not being filled when the project is created.
I have attempted to write some code to uopdate that field after the project is inserted. My logic seems correct however the field (Pse__Primary__Project__C) is not being uopdated with the project name.
Here is the code..
public override void afterInsert(SObject so) { pse__proj__c newProj = (pse__proj__c)so; list <pse__proj__c> projects = [SELECT ID, Name, pse__Opportunity__c FROM pse__proj__c]; list <opportunity> opportunities = [SELECT ID, Name, pse__Primary_Project__c FROM Opportunity]; for (Opportunity opps : opportunities){ if (newProj.Created_by_Opp__c == true) { opps.pse__Primary_Project__c = newProj.id; } }
ANy help would be MUCH appreciated!! THANKS IN ADVANCE!
- Kris Webster
- February 19, 2019
- Like
- 0
Deployment Error PLEASE HELP
Hello Community ! I am attemptimng to deploy a Apex Trigger to update resource requests on Opportunites with a Project name and change the status of the request as well. I want all this to occur when the opportunity hits closed won.
WITH that said I have written the code and have it executing fully in the Sandbox wihtout any erros, and have my code coverage passing 100% when I run the tests for the test class in the SB..
What I am struggling with is deploying the code to Production..
When I attempt to deplot the code I am recieving the following error and I am not sure why i am at all..
Here is my Code
And here is my Test Class to go along with it.
In the test code the test data factory is creating an opp for me, and setting it all up to be ready to close win, and then the test data factory is creating a resource request for me with the associated opportunity on the respource request set to the same opportunity the test data factory just created.
With all this said the error message I am recieving when attempting to deploy the code to Production reads..
"Methods defined as TestMethod do not support Web service callouts
Stack Trace: null"
PLEASE HELP.
I have spent 3 days trying to uncover the error and still nothing, so any help would be MUCH appreciated!
WITH that said I have written the code and have it executing fully in the Sandbox wihtout any erros, and have my code coverage passing 100% when I run the tests for the test class in the SB..
What I am struggling with is deploying the code to Production..
When I attempt to deplot the code I am recieving the following error and I am not sure why i am at all..
Here is my Code
public override void afterUpdate(SObject oldSo, SObject so) { Opportunity newOpp = (Opportunity)so; Opportunity oldOpp = (Opportunity)oldSo; if (newOpp.StageName == Constants.OPTY_STAGE_CLOSED_WON && newopp.Does_Not_Need_Resource_Request__c == FALSE){ list<pse__Resource_Request__c> resourceRequests = [select ID, pse__Opportunity__c, Pse__Status__c FROM pse__Resource_Request__c]; list<opportunity> opps = [Select ID, pse__Primary_Project__c from Opportunity]; boolean isValid = false; for (pse__Resource_Request__c resourceRequest : resourceRequests) { if (resourceRequest.pse__Opportunity__c == newOpp.Id) { //there is a resource request that has the opportunity id of the current opp meaning the opp is valid isValid = true; resourceRequest.pse__Project__c = newOpp.pse__Primary_Project__c; resourceRequest.pse__Status__c = 'Assigned'; } } // if we get out of the loop and isValid is false, it means there were 0 opps that matched the resource request // return error if (!isValid) { so.addError('Please add Resource Requests to this Opportunity before marking it as "Closed Won." If no Resource Requests need to be added to the Opportunity please check the "Does Not Need Resource Request" checkbox in order to Close Win.'); } } }
And here is my Test Class to go along with it.
@isTest static void aftUpTest() { TestDataFactory.initPermissionControls(); //Prep the data TestDataFactory.projects = TestDataFactory.createprojects(2); TestDataFactory.opportunities = TestDataFactory.createOpportunities(2); TestDataFactory.createResourceRequests(1, TestDataFactory.opportunities[0], TRUE); system.test.startTest(); TestDataFactory.opportunities[0].StageName = Constants.OPTY_STAGE_CLOSED_WON; TestDataFactory.opportunities[0].Does_Not_Need_Resource_Request__c = FALSE; TestDataFactory.opportunities[0].Create_Project__c = FALSE; TestDataFactory.opportunities[0].Info_Complete__c = TRUE; TestDataFactory.opportunities[0].Pse__Primary_Project__c = TestDataFactory.projects[0].id; update TestDataFactory.opportunities; system.test.stopTest(); } }
In the test code the test data factory is creating an opp for me, and setting it all up to be ready to close win, and then the test data factory is creating a resource request for me with the associated opportunity on the respource request set to the same opportunity the test data factory just created.
With all this said the error message I am recieving when attempting to deploy the code to Production reads..
"Methods defined as TestMethod do not support Web service callouts
Stack Trace: null"
PLEASE HELP.
I have spent 3 days trying to uncover the error and still nothing, so any help would be MUCH appreciated!
- Kris Webster
- February 18, 2019
- Like
- 0
Trigger not working.. PLEASE HELP
BREAKDOWN
I have a object called Project (pse__Proj__c) that has a lookup field on it called campaign (Campaign__c). I also have another object called Expense Reports (pse__Expense_Report__c) that also has the same lookup field on it, buit with a different API name (Campaign_Expense__c). Basically what I need the code to do is that when a new expense report record is created I need the value that is found in the Campaign (Campaign__c) field (on the project object) to fill the campaign object on the expense report object with the same value.
Here is the code I have, but it is not filling the field on the expense report object with the campaign. PLEASE HELP !
I have a object called Project (pse__Proj__c) that has a lookup field on it called campaign (Campaign__c). I also have another object called Expense Reports (pse__Expense_Report__c) that also has the same lookup field on it, buit with a different API name (Campaign_Expense__c). Basically what I need the code to do is that when a new expense report record is created I need the value that is found in the Campaign (Campaign__c) field (on the project object) to fill the campaign object on the expense report object with the same value.
Here is the code I have, but it is not filling the field on the expense report object with the campaign. PLEASE HELP !
trigger Updatecampaign on pse__Expense_Report__c (before insert,before Update) { // Local catches for bulkified data private map<Id, pse__Proj__c> projMap = new map<Id, pse__Proj__c>(); for (pse__Expense_Report__c er: Trigger.new) ( projectIds.add(er.Campaign_Expense__c); } for{pse__Proj__c pro: [select id, Campaign__c from pse__Proj__c where Campaign__c in :projectIds]} { projMap.put(pro.Campaign__c, projMap) } for (pse__Expense_Report__c er : Trigger.new) { er.Campaign_Expense__c=projMap.get(er.Campaign_Expense__c).Id; } }
- Kris Webster
- November 21, 2018
- Like
- 0
PLEASE HELP (APEX TRIGGER/CLASS)
No one answered me on the previous post and I really need some help here so going for the repost.
Hey guys, I have written this class to extend my Trigger Handler Base code, and have gotten the code to pass without any errors, however it is not doing exactly what I want it to do.
BREAKDOWN
I have a object called Project (pse__Proj__c) that has a lookup field on it called campaign (Campaign__c). I also have another object called Expense Reports (pse__Expense_Report__c) that also has the same lookup field on it, buit with a different API name (Campaign_Expense__c). Basically what I need the code to do is that when a new expense report record is created I need the value that is found in the Campaign (Campaign__c) field (on the project object) to fill the campaign object on the expense report object with the same value.
Here is the code I have, but it is not filling the field on the expense report object with the campaign. PLEASE HELP !
Hey guys, I have written this class to extend my Trigger Handler Base code, and have gotten the code to pass without any errors, however it is not doing exactly what I want it to do.
BREAKDOWN
I have a object called Project (pse__Proj__c) that has a lookup field on it called campaign (Campaign__c). I also have another object called Expense Reports (pse__Expense_Report__c) that also has the same lookup field on it, buit with a different API name (Campaign_Expense__c). Basically what I need the code to do is that when a new expense report record is created I need the value that is found in the Campaign (Campaign__c) field (on the project object) to fill the campaign object on the expense report object with the same value.
Here is the code I have, but it is not filling the field on the expense report object with the campaign. PLEASE HELP !
/************************************************************************************************************************ // Name ExpenseReportHandler // Description Standard trigger handler for ExpenseReportHandler // Revisions 2018-Nov-20 kris.webster@levvel.io Initial version ***********************************************************************************************************************/ public without sharing class ExpenseReportHandler extends TriggerHandlerBase { // Local catches for bulkified data private map<id, pse__Proj__c> projMap = new map<id, pse__Proj__c>(); // key = record id /************************************************************************************************************ // Name bulkBefore // Description Standard implementation of the TriggerHandler.bulkBefore() interface method. *************************************************************************************************************/ public override void bulkBefore() { if (trigger.isInsert || trigger.isUpdate) { set<id> projIds = new set<id>(); for (SObject so : trigger.new) { pse__Expense_Report__c er = (pse__Expense_Report__c)so; if (er.Campaign_Expense__c != null) { projIds.add(er.Campaign_Expense__c); } } // Fetch accounts and their default attributes projMap = new map<Id, pse__Proj__c>( [SELECT Id, Campaign__c FROM pse__Proj__c WHERE Id IN :projIds]); } } /************************************************************************************************************ // Name beforeInsert // Description Standard implementation of the TriggerHandler.afterInsert() interface method. *************************************************************************************************************/ public override void beforeInsert(SObject so) { pse__Expense_Report__c newER = (pse__Expense_Report__c)so; setcamp(newER); } /************************************************************************************************************ // Name beforeUpdate // Description Standard implementation of the TriggerHandler.afterUpdate() interface method. *************************************************************************************************************/ public override void beforeUpdate(SObject oldSo, SObject so) { pse__Expense_Report__c newER = (pse__Expense_Report__c)so; setcamp(newER); } /************************************************************************************************************ // Name queueDeliveryManagerSync // Description Helper method to sync delivery manger to parent opty *************************************************************************************************************/ private void setcamp (pse__Expense_Report__c exprep) { // If the expense reports's campaign is blank, we fill it with the projects campaign if (exprep.Campaign_Expense__c == null && projMap.containsKey(exprep.pse__Project__c)) { exprep.Campaign_Expense__c = projMap.get(exprep.pse__Project__c).Campaign__c; } } }
- Kris Webster
- November 21, 2018
- Like
- 0
Apex Class Functionality
Hey guys, I have written this class to extend my Trigger Handler Base code, and have gotten the code to pass without any errors, however it is not doing exactly what I want it to do.
BREAKDOWN
I have a object called Project (pse__Proj__c) that has a lookup field on it called campaign (Campaign__c). I also have another object called Expense Reports (pse__Expense_Report__c) that also has the same lookup field on it, buit with a different API name (Campaign_Expense__c). Basically what I need the code to do is that when a new expense report record is created I need the value that is found in the Campaign (Campaign__c) field (on the project object) to fill the campaign object on the expense report object with the same value.
Here is the code I have, but it is not filling the field on the expense report object with the campaign. PLEASE HELP !
BREAKDOWN
I have a object called Project (pse__Proj__c) that has a lookup field on it called campaign (Campaign__c). I also have another object called Expense Reports (pse__Expense_Report__c) that also has the same lookup field on it, buit with a different API name (Campaign_Expense__c). Basically what I need the code to do is that when a new expense report record is created I need the value that is found in the Campaign (Campaign__c) field (on the project object) to fill the campaign object on the expense report object with the same value.
Here is the code I have, but it is not filling the field on the expense report object with the campaign. PLEASE HELP !
/************************************************************************************************************************ // Name ExpenseReportHandler // Description Standard trigger handler for ExpenseReportHandler // Revisions 2018-Nov-20 kris.webster@levvel.io Initial version ***********************************************************************************************************************/ public without sharing class ExpenseReportHandler extends TriggerHandlerBase { // Local catches for bulkified data private map<id, pse__Proj__c> projMap = new map<id, pse__Proj__c>(); // key = record id /************************************************************************************************************ // Name bulkBefore // Description Standard implementation of the TriggerHandler.bulkBefore() interface method. *************************************************************************************************************/ public override void bulkBefore() { if (trigger.isInsert || trigger.isUpdate) { set<id> projIds = new set<id>(); for (SObject so : trigger.new) { pse__Expense_Report__c er = (pse__Expense_Report__c)so; if (er.Campaign_Expense__c != null) { projIds.add(er.Campaign_Expense__c); } } // Fetch accounts and their default attributes projMap = new map<Id, pse__Proj__c>( [SELECT Id, Campaign__c FROM pse__Proj__c WHERE Id IN :projIds]); } } /************************************************************************************************************ // Name beforeInsert // Description Standard implementation of the TriggerHandler.afterInsert() interface method. *************************************************************************************************************/ public override void beforeInsert(SObject so) { pse__Expense_Report__c newER = (pse__Expense_Report__c)so; setcamp(newER); } /************************************************************************************************************ // Name beforeUpdate // Description Standard implementation of the TriggerHandler.afterUpdate() interface method. *************************************************************************************************************/ public override void beforeUpdate(SObject oldSo, SObject so) { pse__Expense_Report__c newER = (pse__Expense_Report__c)so; setcamp(newER); } /************************************************************************************************************ // Name queueDeliveryManagerSync // Description Helper method to sync delivery manger to parent opty *************************************************************************************************************/ private void setcamp (pse__Expense_Report__c exprep) { // If the expense reports's campaign is blank, we fill it with the projects campaign if (exprep.Campaign_Expense__c == null && projMap.containsKey(exprep.pse__Project__c)) { exprep.Campaign_Expense__c = projMap.get(exprep.pse__Project__c).Campaign__c; } } }
- Kris Webster
- November 20, 2018
- Like
- 0
Somewhat Simple (I think) TRIGGER HELP
I am not finding a way to solve this issue. I am trying to write a trigger that will populate a contact lookup field with a specific contact. I am struggling to figure out how to code the specific contact into the trigger. WHEN i say a specific contact I mean 1 contact record. SO I want the contact Kris Webster to fill the field Project_Manager__c on the campaign object when a new campaign record is created.. IS THIS POSSIBLE? would I need to build a SOQL of contcats first or what?? I cant seem to find an answer anywhere..
Here is what I have so far.
Here is what I have so far.
trigger CampaignTrigger on Campaign (after insert) { for(Campaign camp:Trigger.New){ if(camp.Project_Manager__c == null) camp.Project_Manager__c = WHAT DO I PUT HERE?? THE USERS ID? } }
- Kris Webster
- October 17, 2018
- Like
- 0
Quick Trigger HELP
I am trying to write a trigger that will populate a contact lookup field with a specific contact. I am struggling to figure out how to code the specific contact into the trigger.
Check out the code and you will see what I mean...
Any help would be MUCH APPRECIATED! Thanks guys!
Check out the code and you will see what I mean...
Any help would be MUCH APPRECIATED! Thanks guys!
trigger CampaignTrigger on Campaign (after insert) { for(Campaign camp:Trigger.New){ if(camp.Project_Manager__c == null) camp.Project_Manager__c = WHAT DO I PUT HERE?? THE USERS ID? } }
- Kris Webster
- October 16, 2018
- Like
- 0
Trigger NOT executing what it should.. PLEASE HELP
I wrote a trigger on a custom object called Project (Pse__proj__c).
Basically I want the trigger to create a new budget (Pse__Budget__c) which is a seperate custom object, every time the checkbox "pro.Created_by_Opp__c == True"
My trigger is not getting any errors in the dev org but it is not creating a new budget when the checkbox is checked...
Any help would be much appreciated !!
Basically I want the trigger to create a new budget (Pse__Budget__c) which is a seperate custom object, every time the checkbox "pro.Created_by_Opp__c == True"
My trigger is not getting any errors in the dev org but it is not creating a new budget when the checkbox is checked...
Any help would be much appreciated !!
trigger CreateBudgetForProject on pse__Proj__c (after insert){ List<pse__Budget__c> Listbud = new List<pse__Budget__c>(); for(pse__Proj__c pro : trigger.new) { if(Trigger.isUpdate) { if(pro.Created_by_Opp__c == True) { //Fields that will be filled on Budget listbud.add(new pse__Budget__c(name = pro.name, pse__Amount__c = pro.Product_Budget_MAP__c, pse__Project__c = pro.Name, pse__Type__c = 'Customer Purcahse Order', pse__Status__c = 'Approved', pse__Effective_Date__c = pro.pse__Start_Date__c )); } if (Trigger.isInsert) { if(pro.Created_by_Opp__c == True) { //Fill Mandatory Fields on Associated Budget Object listbud.add(new pse__Budget__c(name = pro.name, pse__Amount__c = pro.Product_Budget_MAP__c, pse__Project__c = pro.Name, pse__Type__c = 'Customer Purcahse Order', pse__Status__c = 'Approved', pse__Effective_Date__c = pro.pse__Start_Date__c )); } } } if(listbud.size() > 0) { insert listbud; } } }
- Kris Webster
- October 14, 2018
- Like
- 0
Basic Trigger HELP !
I am trying to write a trigger to do the following..
I have a custom object called Project with the API Name of - pse__Proj__c
I have another custom object called Budget with the API Name of - pse__Budget__c
What I want to do with the trigger is..
When a new project is created I want the project name to automatically fill a field on the budget object called project. The project field on the budget object is a lookiup field to the project object and has the API name of pse__Project__c.
Later on I want to also incorporate the trigger to update a field on the budget object called Amount, that has the API name of
pse__Amount__c with the value found on the Project object in the field called Prouct Budget MAP with the API name of Product_Budget_MAP__c. That can wait but I do need the first step implemented in order to move forward.
HERE IS WHAT I HAVE SO FAR... Any help is much appreciated!!
trigger updateBudgetProject on pse__Budget__c (after insert){
List<pse__Budget__c> BudgetToUpdate = new list<pse__Budget__c>();
for(pse__Budget__c bud : [select Id, pse__Proj__c.Id From pse__Budget__c Where Id IN : trigger.newMap.keyset()]){
bud.pse__Project__c = bud.pse__Proj__c.name;
BudgetsToUpdate.add(bud);
}
if(!BudgetsToUpdate.isEmpty())
update BudgetsToUpdate;
I have a custom object called Project with the API Name of - pse__Proj__c
I have another custom object called Budget with the API Name of - pse__Budget__c
What I want to do with the trigger is..
When a new project is created I want the project name to automatically fill a field on the budget object called project. The project field on the budget object is a lookiup field to the project object and has the API name of pse__Project__c.
Later on I want to also incorporate the trigger to update a field on the budget object called Amount, that has the API name of
pse__Amount__c with the value found on the Project object in the field called Prouct Budget MAP with the API name of Product_Budget_MAP__c. That can wait but I do need the first step implemented in order to move forward.
HERE IS WHAT I HAVE SO FAR... Any help is much appreciated!!
trigger updateBudgetProject on pse__Budget__c (after insert){
List<pse__Budget__c> BudgetToUpdate = new list<pse__Budget__c>();
for(pse__Budget__c bud : [select Id, pse__Proj__c.Id From pse__Budget__c Where Id IN : trigger.newMap.keyset()]){
bud.pse__Project__c = bud.pse__Proj__c.name;
BudgetsToUpdate.add(bud);
}
if(!BudgetsToUpdate.isEmpty())
update BudgetsToUpdate;
- Kris Webster
- October 12, 2018
- Like
- 0
Schedule REST API Callout HELP
Good afternoon,
I have a API call class that is working as I need it to, however I am not trying to get the class to execute every night at 2 AM. I am trying to implement a schedulable class to call the API class and make it execute every night, but am a little unsure how to do this..
Here is my REST API class
For anyone that has implemented a way to have an API call excecute every night on a daily basis please share your wisdome with me !!
Thanks in advance !!
I have a API call class that is working as I need it to, however I am not trying to get the class to execute every night at 2 AM. I am trying to implement a schedulable class to call the API class and make it execute every night, but am a little unsure how to do this..
Here is my REST API class
string url = *****; Integer int1 = 0; String myProcedure1() { Http http = new Http(); HttpRequest request = new HttpRequest(); request.setHeader('Authorization', 'Bearer ****); request.setEndpoint(url); request.setMethod('GET'); HttpResponse response = http.send(request); // If the request is successful, parse the JSON response. if (response.getStatusCode() == 200) { // Deserializes the JSON string into collections of posts. Map<String,Object> wrapper = (Map<String,Object>) JSON.deserializeUntyped(response.getBody()); if (wrapper.containsKey('data')) { Map<String, Object> wrapper2 = (Map<String,Object>) wrapper.get('data'); if(wrapper2.containsKey('data')) { List<Object> people = (List<Object>)wrapper2.get('data'); for (Object peopleWrapper : people) { Map<String,Object> Employees = (Map<String,Object>) peopleWrapper; if(Employees.containsKey('last_name')){ String ZenefitsLastName = (String) Employees.get('last_name'); String ZenefitsFirstName = (String) Employees.get('first_name'); String ZenefitseEmployeeId = (String) Employees.get('id'); String ZenefitsEmail = (String) Employees.get('work_email'); List<Contact> contactList = [SELECT Id, FirstName, LastName, Zenefits_ID__c, Email FROM Contact WHERE Email = :ZenefitsEmail LIMIT 200]; List<Contact> contactsToUpdate = new List<Contact>(); for(Contact con : contactList){ con.Zenefits_Id__c = ZenefitseEmployeeId; contactsToUpdate.add(con); } update contactsToUpdate; //we now need to find all contacts in SF that match the contacts in Employees //once we have matches we need to synce each ID system.debug('Employees ' + Employees); system.debug('last name ' + ZenefitsLastName); system.debug('Employee id ' + ZenefitseEmployeeId); system.debug('first name ' + ZenefitsFirstName); system.debug('Contact list ' + contactList); system.debug('TEST ' + contactsToUpdate); } } } return null; } return null; } return null; } void myProcedure2() { while (url != null) { System.debug('BEFORE URL: ' + url); url = myProcedure1(); System.debug('AFTER URL: ' + url); } } myProcedure2();I have gone ahead and taken out the URL and the Bearer headers for privacy purposes, but all else is there.
For anyone that has implemented a way to have an API call excecute every night on a daily basis please share your wisdome with me !!
Thanks in advance !!
- Kris Webster
- October 09, 2019
- Like
- 0
API Query HELP
I am trying to query salesforce data based on information that I am pulling from our HR system via a REST API callout to the HR system.
Basically I am tring to find all contacts in my Salesforce org where the first name = the first name in the API Call. I know that first name is not specific enough, but I am starting here and once I can get records to match I will use a more unique identifier.
Here is my code. I NEED HELP WITH LINE 28! I have left out authorization lines for privacy sake.
Basically I am tring to find all contacts in my Salesforce org where the first name = the first name in the API Call. I know that first name is not specific enough, but I am starting here and once I can get records to match I will use a more unique identifier.
Here is my code. I NEED HELP WITH LINE 28! I have left out authorization lines for privacy sake.
request.setMethod('GET'); HttpResponse response = http.send(request); // If the request is successful, parse the JSON response. if (response.getStatusCode() == 200) { // Deserializes the JSON string into collections of posts. Map<String,Object> wrapper = (Map<String,Object>) JSON.deserializeUntyped(response.getBody()); if (wrapper.containsKey('data')) { Map<String, Object> wrapper2 = (Map<String,Object>) wrapper.get('data'); if(wrapper2.containsKey('data')) { List<Object> people = (List<Object>)wrapper2.get('data'); for (Object peopleWrapper : people) { Map<String,Object> Employees = (Map<String,Object>) peopleWrapper; if(Employees.containsKey('last_name')){ String ZenefitsLastName = (String) Employees.get('last_name'); String ZenefitsFirstName = (String) Employees.get('first_name'); String ZenefitseEmployeeId = (String) Employees.get('id'); List<Contact> contactList = [SELECT Id, FirstName, LastName FROM Contact WHERE FirstName = Employees.get('first_name') LIMIT 200]; //we now need to find all contacts in SF that match the contacts in Employees //once we have matches we need to synce each ID system.debug('Employees ' + Employees); system.debug('last name ' + ZenefitsLastName); system.debug('Employee id ' + ZenefitseEmployeeId); system.debug('first name ' + ZenefitsFirstName); system.debug('Contact list ' + contactList); } } } return null; } return null; } return null; }
- Kris Webster
- October 08, 2019
- Like
- 0
Schedule Apex class to query Assignments and add Assignment to Contact record.
I am trying to create an Apex class that will run every night and update a field on Contact based on specidic criteria.
Basically what I need to happen is for the system to query all assignemnts (pse__assignment__c) in the system with an end date (pse__End_Date__c) greater than TODAY (today__c)
I then need to add that assignemnt to a custom field I have created on Contact if the assignment passes the criteria. If there are no assignments for the specific contact then I need the assignment field to be NULL.
There is a lookup relationship between Assignemtn and Contact. In my code I think I am querying the assignments correctly but I am strugling with figuring out how to then associate that specific assignment with the correct contact. I am also struggling with how to make this Class a schedulable class that I am able to schedule to run every night.
Here is my code so far.
Any help would be GREATLY APPRECIATED
Basically what I need to happen is for the system to query all assignemnts (pse__assignment__c) in the system with an end date (pse__End_Date__c) greater than TODAY (today__c)
I then need to add that assignemnt to a custom field I have created on Contact if the assignment passes the criteria. If there are no assignments for the specific contact then I need the assignment field to be NULL.
There is a lookup relationship between Assignemtn and Contact. In my code I think I am querying the assignments correctly but I am strugling with figuring out how to then associate that specific assignment with the correct contact. I am also struggling with how to make this Class a schedulable class that I am able to schedule to run every night.
Here is my code so far.
Any help would be GREATLY APPRECIATED
public class AssignmentToContact implements Database.Batchable<sObject> { global Database.queryLocator start(Database.BatchableContext ctx ) { list<pse__Assignment__c> aid=New list<pse__Assignment__c>(); list<Contact> updatecontact = new list<Contact>(); for(pse__Assignment__c ass: Trigger.new){ if(ass.pse__End_Date__c >= today__c && ass.pse__Is_Billable__c = TRUE){ aid.add(ass.id); } list<Contact> contactlist=[SELECT Id,Assignment__c FROM Contact WHERE id = :aid]; for(Contact con: contactlist){ con.Assignment__c=ass.Id; updatecontact.add(con); } } update updatecontact; } } //IF THE list is empty then the field on CONTACT should be NULL
- Kris Webster
- July 31, 2019
- Like
- 0
Deployment Error PLEASE HELP
Hello Community ! I am attemptimng to deploy a Apex Trigger to update resource requests on Opportunites with a Project name and change the status of the request as well. I want all this to occur when the opportunity hits closed won.
WITH that said I have written the code and have it executing fully in the Sandbox wihtout any erros, and have my code coverage passing 100% when I run the tests for the test class in the SB..
What I am struggling with is deploying the code to Production..
When I attempt to deplot the code I am recieving the following error and I am not sure why i am at all..
Here is my Code
And here is my Test Class to go along with it.
In the test code the test data factory is creating an opp for me, and setting it all up to be ready to close win, and then the test data factory is creating a resource request for me with the associated opportunity on the respource request set to the same opportunity the test data factory just created.
With all this said the error message I am recieving when attempting to deploy the code to Production reads..
"Methods defined as TestMethod do not support Web service callouts
Stack Trace: null"
PLEASE HELP.
I have spent 3 days trying to uncover the error and still nothing, so any help would be MUCH appreciated!
WITH that said I have written the code and have it executing fully in the Sandbox wihtout any erros, and have my code coverage passing 100% when I run the tests for the test class in the SB..
What I am struggling with is deploying the code to Production..
When I attempt to deplot the code I am recieving the following error and I am not sure why i am at all..
Here is my Code
public override void afterUpdate(SObject oldSo, SObject so) { Opportunity newOpp = (Opportunity)so; Opportunity oldOpp = (Opportunity)oldSo; if (newOpp.StageName == Constants.OPTY_STAGE_CLOSED_WON && newopp.Does_Not_Need_Resource_Request__c == FALSE){ list<pse__Resource_Request__c> resourceRequests = [select ID, pse__Opportunity__c, Pse__Status__c FROM pse__Resource_Request__c]; list<opportunity> opps = [Select ID, pse__Primary_Project__c from Opportunity]; boolean isValid = false; for (pse__Resource_Request__c resourceRequest : resourceRequests) { if (resourceRequest.pse__Opportunity__c == newOpp.Id) { //there is a resource request that has the opportunity id of the current opp meaning the opp is valid isValid = true; resourceRequest.pse__Project__c = newOpp.pse__Primary_Project__c; resourceRequest.pse__Status__c = 'Assigned'; } } // if we get out of the loop and isValid is false, it means there were 0 opps that matched the resource request // return error if (!isValid) { so.addError('Please add Resource Requests to this Opportunity before marking it as "Closed Won." If no Resource Requests need to be added to the Opportunity please check the "Does Not Need Resource Request" checkbox in order to Close Win.'); } } }
And here is my Test Class to go along with it.
@isTest static void aftUpTest() { TestDataFactory.initPermissionControls(); //Prep the data TestDataFactory.projects = TestDataFactory.createprojects(2); TestDataFactory.opportunities = TestDataFactory.createOpportunities(2); TestDataFactory.createResourceRequests(1, TestDataFactory.opportunities[0], TRUE); system.test.startTest(); TestDataFactory.opportunities[0].StageName = Constants.OPTY_STAGE_CLOSED_WON; TestDataFactory.opportunities[0].Does_Not_Need_Resource_Request__c = FALSE; TestDataFactory.opportunities[0].Create_Project__c = FALSE; TestDataFactory.opportunities[0].Info_Complete__c = TRUE; TestDataFactory.opportunities[0].Pse__Primary_Project__c = TestDataFactory.projects[0].id; update TestDataFactory.opportunities; system.test.stopTest(); } }
In the test code the test data factory is creating an opp for me, and setting it all up to be ready to close win, and then the test data factory is creating a resource request for me with the associated opportunity on the respource request set to the same opportunity the test data factory just created.
With all this said the error message I am recieving when attempting to deploy the code to Production reads..
"Methods defined as TestMethod do not support Web service callouts
Stack Trace: null"
PLEASE HELP.
I have spent 3 days trying to uncover the error and still nothing, so any help would be MUCH appreciated!
- Kris Webster
- February 18, 2019
- Like
- 0
Quick Trigger HELP
I am trying to write a trigger that will populate a contact lookup field with a specific contact. I am struggling to figure out how to code the specific contact into the trigger.
Check out the code and you will see what I mean...
Any help would be MUCH APPRECIATED! Thanks guys!
Check out the code and you will see what I mean...
Any help would be MUCH APPRECIATED! Thanks guys!
trigger CampaignTrigger on Campaign (after insert) { for(Campaign camp:Trigger.New){ if(camp.Project_Manager__c == null) camp.Project_Manager__c = WHAT DO I PUT HERE?? THE USERS ID? } }
- Kris Webster
- October 16, 2018
- Like
- 0
Trigger NOT executing what it should.. PLEASE HELP
I wrote a trigger on a custom object called Project (Pse__proj__c).
Basically I want the trigger to create a new budget (Pse__Budget__c) which is a seperate custom object, every time the checkbox "pro.Created_by_Opp__c == True"
My trigger is not getting any errors in the dev org but it is not creating a new budget when the checkbox is checked...
Any help would be much appreciated !!
Basically I want the trigger to create a new budget (Pse__Budget__c) which is a seperate custom object, every time the checkbox "pro.Created_by_Opp__c == True"
My trigger is not getting any errors in the dev org but it is not creating a new budget when the checkbox is checked...
Any help would be much appreciated !!
trigger CreateBudgetForProject on pse__Proj__c (after insert){ List<pse__Budget__c> Listbud = new List<pse__Budget__c>(); for(pse__Proj__c pro : trigger.new) { if(Trigger.isUpdate) { if(pro.Created_by_Opp__c == True) { //Fields that will be filled on Budget listbud.add(new pse__Budget__c(name = pro.name, pse__Amount__c = pro.Product_Budget_MAP__c, pse__Project__c = pro.Name, pse__Type__c = 'Customer Purcahse Order', pse__Status__c = 'Approved', pse__Effective_Date__c = pro.pse__Start_Date__c )); } if (Trigger.isInsert) { if(pro.Created_by_Opp__c == True) { //Fill Mandatory Fields on Associated Budget Object listbud.add(new pse__Budget__c(name = pro.name, pse__Amount__c = pro.Product_Budget_MAP__c, pse__Project__c = pro.Name, pse__Type__c = 'Customer Purcahse Order', pse__Status__c = 'Approved', pse__Effective_Date__c = pro.pse__Start_Date__c )); } } } if(listbud.size() > 0) { insert listbud; } } }
- Kris Webster
- October 14, 2018
- Like
- 0