-
ChatterFeed
-
30Best Answers
-
0Likes Received
-
0Likes Given
-
23Questions
-
421Replies
Referencing sObject within another sObject
I'm in the process of trying to consolidate the SOQL calls within a trigger of a particularly difficult sObject. This sObject has enough code running on it that we're pretty regularly hitting the 101 error--so it's time to clean up and bulkify where possible.
I've run the following to fill a map with an sobject, and the children of that sobject. Let's assume for the moment that Service_Order_Line is a child of Service_Order with a many-to-one relationship, and I've filtered this down so I'm only getting one Service_Order and maybe 5 or 10 Service_Order_Lines:
map<ID, Service_Order__c> testResults = new map<ID, Service_Order__c>([select ID, Name, (select ID, Name from Service_Order_Line__r) from Service_Order__c']);
Further down in the trigger, I'll need to reference the child objects, but I can't seem to find a syntax to make it work. How would I write the following to loop through the children of testResults?
for(Service_Order_Line childrenOfTestResults : testResults.Service_Order_Line__r) {
system.debug(childrenOfTestResults.Name);
}
- Jared Rosenberg
- September 24, 2019
- Like
- 0
- Continue reading or reply
simulation of code in Salesforce for a request in Postman
I exeucte a postman request to get the token.
I was writing a code for authenticating the API in slaesforce, but found that the headers are not correct.
I tried to get the headers by other way.
How can i write the code for first part of the screen shot, ?
- Ab
- September 23, 2019
- Like
- 0
- Continue reading or reply
How to check if an email contains the right format
if(email__c.contains('@gmail.com'){} but then I realized that this may not be enough because someone could potentially enter an email of gmail.com@hotmail.com for example. So I want to see what I can write in apex to check if the email is in the format ###@gmail.com
Thank you
- Afzaal Hassan
- August 28, 2019
- Like
- 0
- Continue reading or reply
A developer needs to create an audit trail for records that are sent to the recycle bin. Which type of trigger is most appropriate to create?
before delete
after delete
before undelete
- Kristiana Granger
- August 13, 2019
- Like
- 0
- Continue reading or reply
Limits on Batch Apex with Trigger: Will it be 5 or 105?
I'm new to developing and trying to determine if I will get errors thrown in my batch apex code. The purpose is to: upon deactivation of a user (trigger, which I understand isn't best practice but don't know another way the batch can be automatically started w/o checking for deactivated users every night), all of the leads of deactivated user are queried to change the OwnerId to a catchall user. The trick is that one user may have as many as 200,000 leads that need to be updated, hence why I am using batch apex. Two questions:
1. How many batch jobs will be activated with each deactivated user? (I think the answer is one?)
2. Will the batch job be sent to the Flex Queue as 'holding' and then to active, giving the org 105 possible batch jobs to be held/processed at once before throwing errors, or will it bypass Flex Queue, thereby limiting the org to only 5 batch jobs at a time?
I hope my questions make sense, and I appreciate any help. I have spent many hours researching this as a newbie. In case it's relevant, my code is below:
Trigger:
trigger BatchUpdateTrigger2 on User (after update) { //Map will keep deactivated users and their Id's, to be used later in batch Apex Map<id, User> DeactivatedUsers = new Map<id, User>(); //Check all users in trigger, first if the IsActive button has been newly changed and if it now says that the user is not active for (Integer i=0;i<Trigger.new.size();i++) { if (Trigger.new[i].IsActive!=Trigger.old[i].IsActive && Trigger.new[i].IsActive == false) { DeactivatedUsers.put(Trigger.new[i].Id, Trigger.new[i]); } } // Make sure that there are users to be processed if (DeactivatedUsers.size() > 0) { BatchUpdateLeads objBatchUpdateLeads=new BatchUpdateLeads(DeactivatedUsers); Database.executeBatch(objBatchUpdateLeads); } }
Batch Apex Class:
global class BatchUpdateLeads implements Database.Batchable<SObject> { //Save a public variable to hard-code the catchall user that will become lead owner public Id GenericUserId = '0054P000009pLkrQAE'; //map of userid - user that retrieves deactivated user(s) from previous trigger Map<Id, User> DeactivatedUsersMap = new Map<Id, User>(); global BatchUpdateLeads(Map<Id, User> DeactivatedUsers) { DeactivatedUsersMap = DeactivatedUsers; } //Search for the leads whose OwnerId is the deactivated user(s) global Database.QueryLocator start(Database.BatchableContext BC) { return DataBase.getQueryLocator([SELECT Id, OwnerId FROM Lead WHERE OwnerId IN : DeactivatedUsersMap.keySet()]); } //For leads whose owner was deactivated, change OwnerId to the catchall user global void execute(Database.BatchableContext BC, List<sObject> scope){ List<Lead> leads = (List<lead>)scope; for (Lead l: leads){ l.OwnerId = GenericUserId;} //Check that there are leads to be updated, then update if (leads.size() > 0){ update leads; } } global void finish(Database.BatchableContext BC) { //Send an email to system admin after the batch completes (fill in email) Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {'xxxxxxx@gmail.com'}; mail.setToAddresses(toAddresses); mail.setSubject('Apex Batch Job is done'); mail.setPlainTextBody('The Batch Apex Job Processed Successfully'); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } }
- Sierra VP
- August 12, 2019
- Like
- 0
- Continue reading or reply
How do i write a test class for Batchable Apex
This is my Class
global class HealthUpdaterBatchable implements Database.Batchable<sObject> { global Database.QueryLocator start(Database.BatchableContext BC) { String query = 'SELECT Id FROM HealthScore__c'; return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<HealthScore__c> hsList) { for(HealthScore__c hs : hsList) { hs.id = hs.id; } try { update hsList; } catch(Exception e) { System.debug(e); } } global void finish(Database.BatchableContext BC) { } }This is my test class so far
private class HealthUpdaterBatchableTest { static testmethod void test() { HealthScore__c[] hsList = new List(); for (Integer i=0;i<200;i++) { HealthScore__c m = new Healthscore__c(); hsList.add(m); } insert hsList; Test.startTest(); HealthUpdaterBatchable c = new HealthUpdaterBatchable(); Database.executeBatch(c); Test.stopTest(); HealthScore__c[] hsUpdatedList = [SELECT Id FROM HealthScore__c]; System.assert(hsUpdatedList[0]); } }Im getting a few errors
- Expecting < but was ( -Line 6
- Invalid type: HealthScore - Line 18
- Method does not exist or incorrect signature: void assert(Healthscore) from the type System. - Line 19.
- JoshTonks
- August 12, 2019
- Like
- 0
- Continue reading or reply
Need help with Contact/Event trigger
Event 1: tied to Contact A & Contact B; sales_within_1_year = $0
Event 2: tied to Contact A & Contact C; sales_within_1_year = $10
Contact A sales changes from $100 to $200.
Event 1: new sales_within_1_year = $100
Event 2: new sales_within_1_year = $110
If the sales for Contact B or C changed, it would only affect the event they are tied to.
I thought my trigger would work, and it does when I change a contact's sales number individually. But when I bulk update contacts, none of the sales_within_1_year numbers change. I was wondering if someone could help me through this. Thanks!
Here is my trigger:
trigger EventSales on Contact (before update) {
//Create a list of contact IDs that have updating sales
List<Id> contactIds = new List<Id>();
for(Contact con : trigger.new) {
if(Trigger.newMap.get(con.Id).Sales__c == NULL) return;
else if(trigger.newMap.get(con.Id).Sales__c == 0) return;
else if(trigger.oldMap.get(con.Id).Sales__c == NULL) {
contactIds.add(con.Id);
}
else if(trigger.newMap.get(con.Id).Sales__c !=
trigger.oldMap.get(con.Id).Sales__c) {
contactIds.add(con.Id);
}
}
//Create a list of event relations (contact-event pairs) for updating contacts
List<EventRelation> evRel = [SELECT EventId, RelationId
FROM EventRelation
WHERE RelationId IN :contactIds];
//Create a map of the updating contacts and their related events
Map<Id, List<Id>> contactEvents = new Map<Id, List<Id>>();
//Create a list of event Ids that are going to be updated
List<Id> eventIds = new List<Id>();
//Put the contact Id and event Id in the map for events that have updating contacts
for(EventRelation rel :evRel) {
if(contactEvents.containsKey(rel.RelationId)) {//If the contact is already in the map
List<Id> relatedEv = contactEvents.get(rel.RelationId);//Grab the list of events tied to the contact
relatedEv.add(rel.EventId);//Add the new event to the list
contactEvents.put(rel.RelationId, relatedEv);//Put the updated list into the map
}
else {//If the contact isn't in the map
contactEvents.put(rel.RelationId, new List<Id>{rel.EventId});//Put the contact and event into the map
}
//Add the updating event to the eventIds list
if(eventIds.contains(rel.EventId)) return;
else eventIds.add(rel.EventId);
}
//Create a list of events that are going to be updated
List<Event> listEventsMaker = [SELECT Id, Sales_within_1_year__c
FROM Event
WHERE Id IN :eventIds
AND EndDateTime = LAST_N_DAYS:365];
List<Event> listEvents = new List<Event>();
for(Event ev :listEventsMaker) {
if(listEvents.contains(ev)) return;
else listEvents.add(ev);
}
//Keep a list of events to update
List<Event> changedEvents = new List<Event>();
//Update the sales amounts for the events
for(Id con :contactEvents.keySet()) {//For each contact in the map
List<Id> thisContact = new List<Id>();//Create a list of events tied to this specific contact
Contact oldCon = trigger.oldMap.get(con); //create a record for the contact pre-update
Contact newCon = trigger.newMap.get(con); //create a record for the contact post-update
if(newCon.Sales__c == NULL) return;
else if(newCon.Sales__c == 0) return;
else if(oldCon.Sales__c == NULL) {
for(Id event :contactEvents.get(con)) {
thisContact.add(event);
}
for(Event ev :listEventsMaker) {
if(thisContact.contains(ev.Id)) {
changedEvents.add(ev);
if(ev.Sales_within_1_Year__c == NULL) {
ev.Sales_within_1_Year__c = newCon.Sales__c;
}
else ev.Sales_within_1_Year__c += newCon.Sales__c;
}
}
}
else if(oldCon.Sales__c
!= newCon.Sales__c) {
for(Id event :contactEvents.get(con)) {
thisContact.add(event);
}
for(Event ev :listEventsMaker) {
if(thisContact.contains(ev.Id)) {
changedEvents.add(ev);
if(ev.Sales_within_1_Year__c == NULL) {
ev.Sales_within_1_year__c = (newCon.Sales__c
- oldCon.Sales__c);
}
else ev.Sales_within_1_Year__c += (newCon.Sales__c
- oldCon.Sales__c);
}
}
}
}
update changedEvents;
}
- Mitch Morrison
- August 12, 2019
- Like
- 0
- Continue reading or reply
Tests not entering into if/else
I needed to modify an apex class I deployed to production before.
The problem is that the code coverage is now 45% and I don't understand why it doesn't enter if neither if nor else.
I'm doing a callout into a future method, using HttpCalloutMock.
Main class example :
Test class :
Test.startTest(); Test.setMock(HttpCalloutMock.class, new AppelAPIMock()); ExpeditionSearchDPD.updateExpe(expeditions); Test.stopTest();AppelAPIMock :
@isTest global with sharing class AppelAPIMock implements HTTPCalloutMock{ global HTTPResponse respond(HTTPRequest req){ HttpResponse res = new HTTPResponse(); res.setHeader('Content-Type', 'text/xml'); res.setBody('<?xml version="1.0" encoding="utf-8"?>' + '<soap12:Envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">' + '<soap12:Body>' + '<getShipmentTraceResponse xmlns="http://www.cargonet.software/">' + '<getShipmentTraceResult>' + '<ShippingDate>02.08.2019</ShippingDate>' + '<DeliveryDate>05.08.2019</DeliveryDate>' + '<Weight>0</Weight>' + '</getShipmentTraceResult>' + '</getShipmentTraceResponse>' + '</soap12:Body>' + '</soap12:Envelope>'); res.setStatusCode(200); return res; } }Thank you for your answers
- Valentin F.
- August 12, 2019
- Like
- 0
- Continue reading or reply
Batch Apex Class - How to pass the String and Use into Query inside the Execute Function(Batch method).
I Have an Visual force page with some Set of List and String.
I have given those List and string While calling the Batch apex
Extension_Batch batch = new CloneNSTExtension_Batch(List name,String name); batch.executeBatch(batch);My clarification is how to take the String name inside the excute method in batch apex.Because,those string(which have value from the normal apex class) I have added as the Condition value in query.
Please advice.
Thanks in advance
Sumitha P
- sumitha
- August 12, 2019
- Like
- 0
- Continue reading or reply
SOQL Query to return matching fields
- Nevin O'Regan 3
- August 07, 2019
- Like
- 0
- Continue reading or reply
How to use Standard Stylesheet and External Stylesheet simultaneously ?
I am new with salesforce and I am still my learning phase.
I just wanted to know whether could we use VF standard stylesheet and external stylesheet such as bootstrap simultaneously? If yes, please let me know how to use??
Thanx in advance.
- Ashish Kumar
- June 17, 2016
- Like
- 0
- Continue reading or reply
Webservice Test Class help?
Class:
global class JIRAWebserviceCalloutSyncStatus { @future (callout=true) WebService static void syncstatus(String status, String jiraKey) { //Modify these variables: String username = 'salesforceconnector'; String password = 'xxxxxx'; String jiraURL = 'https://xxxxx.xxxxxx.com'; String transitionId; //Map Salesforce Status to JIRA transition Id: if (status == 'Waiting on Risk') { // Salesforce.com Status transitionId = '181'; // JIRA transition ID } else if (status == 'Waiting on Customer') { transitionId = '21'; } else if (status == 'Active') { transitionId = '161'; } //Construct HTTP request and response HttpRequest req = new HttpRequest(); HttpResponse res = new HttpResponse(); Http http = new Http(); //Construct Authorization and Content header Blob headerValue = Blob.valueOf(username+':'+password); String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue); req.setHeader('Authorization', authorizationHeader); req.setHeader('Content-Type','application/json'); //Construct Endpoint String endpoint = jiraURL+'/rest/api/2/issue/'+jiraKey+'/transitions'; //Set Method and Endpoint and Body req.setMethod('POST'); req.setEndpoint(endpoint); req.setBody('{ \"transition\": {\"id\": \"'+transitionId+'\"}}'); try { //Send endpoint to JIRA res = http.send(req); } catch(System.CalloutException e) { System.debug(res.toString()); } } }
Trigger:
trigger SyncStatus on Case (after update) { //Identify profile name to be blocked from executing this trigger String JIRAAgentProfileName = 'JIRA Agent'; List<Profile> p = [SELECT Id FROM Profile WHERE Name=:JIRAAgentProfileName]; //Check if specified Profile Name exist or not if(!p.isEmpty()) { //Check if current user's profile is catergorized in the blocked profile if(UserInfo.getProfileId()!= String.valueOf(p[0].id)) { for (Case c : Trigger.new) { //Define parameters to be used in calling Apex Class String status = c.Status; String jiraKey = c.JIRA_Key__c; JIRAWebserviceCalloutSyncStatus.syncstatus(status, jiraKey); } } } }
Test Class:
@isTest public class TestJIRAWebserviceCalloutSyncStatus { static testMethod void TestJIRAWebserviceCalloutSyncStatus(){ Test.startTest(); JIRAWebserviceCalloutSyncStatus.SyncStatus(); Test.stopTest(); } }
- Frank Jordan 14
- June 16, 2016
- Like
- 0
- Continue reading or reply
Soap Response: XmlStreamReader Method Help Syntax
I am getting an error of " Illegal State: Current state is not among the states START_ELEMENT , ATTRIBUTEvalid for getAttributeValue()".
Thanks for the help!
HTTP/1.1 200 OK Content-Type: application/soap+xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> <soap12:Body> <clientInsertResponse xmlns="http://amsservices.com/"> <clientInsertResult> <Success>boolean</Success> <SagittaId>long</SagittaId> <SagittaCode>string</SagittaCode> <Errors> <Errors> <Code>int</Code> <Message>string</Message> </Errors> <Errors> <Code>int</Code> <Message>string</Message> </Errors> </Errors> </clientInsertResult> </clientInsertResponse> </soap12:Body> </soap12:Envelope>
- Terminusbot
- June 15, 2016
- Like
- 0
- Continue reading or reply
How get field ID for a custom link?
I want to add a new filter condition to a report when I visit it via a custom link. I know how to get the field ID for a custom object's fields. I know how to get the field IDs for standard objects. How do I get the ID for a custom object's standard fields? Specifically, I want to use the Name field of an object as the field to filter on.
So far, my added filter condition hasn't even appeared when I click the link. I suspect this is because I've failed to find the proper ID thus far. I am filling in parameter pc4 with the ID value, Of course, pn4, and pv4 are getting appropriate values too.
- bperry8086
- June 07, 2013
- Like
- 0
- Continue reading or reply
Formatting outputText to show respective users Time Zone
Hello,
I found a previous post referencing this but cannot seem to get it to work in my org. I am already using an Extension on this page to reference users information from names in a picklist. I have tried to put two extensions, such as extensions="ProjectConfirmationEXT,timeZone" but get the following error, "Error: Unknown constructor 'timeZone.timeZone(ApexPages.StandardController controller)'"
Can someone help me figure out what I am doing wrong?
VisualForce page
<apex:page standardController="Job__c" extensions="ProjectConfirmationEXT" showHeader="false" renderAs="pdf"> <apex:dataTable style="font-family: Calibri, sans-serif;" id="EventTable" value="{!Job__c.Events}" var="e" width="100%" rowClasses="odd,even" styleClass="tableClass" cellpadding="4" border="1"> <apex:column headerValue="Date"> <apex:outputField value="{0,date,MM/dd/yyyy}"> <apex:param value="{!e.StartDateTime}" /> </apex:outputField> </apex:column> <apex:column headerValue="Start Time"> <apex:outputText value="{0,time,HH:MM}"> <apex:param value="{!e.StartDateTime}" /> </apex:outputText> </apex:column> <apex:column headerValue="End Time"> <apex:outputText value="{0,time,HH:MM}"> <apex:param value="{!e.EndDateTime}" /> </apex:outputText> </apex:column> </apex:dataTable>
timeZone EXT
public class timeZone { public String dateTimeValue { get; set; } public timeZone() { dateTimeValue = System.Now().format('MM/dd/yy HH:mm a', 'PST');//GMT } }
- acrozier
- May 26, 2011
- Like
- 0
- Continue reading or reply
Trouble adding image to Visualforce page
I'm attempting to add my company logo to a visual force page, which is then being rendered as a pdf, but have not been successful. I've attempted to do so in three ways:
Image is on a website:
<apex:image url="http://www.tsysacquiring.com/graphics/logos/tsysacquiring_top_logo.gif" width="220" height="55"/>
Image has been loaded into Salesforce into documents, and is in the /alva/ folder:
<apex:image value="/alva/TSYS_logo_for_TSYS_Sales_App.jpg" width="220" height="55"/>
Image is on my C:\drive:
<apex:image value="C:\data\TSYS_Logo_for_TSYS_Sales_App.jpg" width="220" height="55"/>
All three attempts have resulted in a broken image icon being displayed. This seems like a very straightforward thing I'm attempting, and I'd expect it to be rather simple. Any one have a syntax example that they know works.
Thanks!
- dhueber@tsys.com
- May 24, 2010
- Like
- 0
- Continue reading or reply
Restricting trigger to Record Type!
Hey Guys,
Looking for a way to restrict a trigger when a specific opportunity record type isn't selected.
My Code:
trigger Opportunity on Opportunity (after insert) {
List<OpportunityLineItem> blineItems = new List<OpportunityLineItem>();
for(Opportunity o : trigger.new){
string a;
string b = o.Product2__c;
String c = o.RecordTypeId;
if(c == '012T00000000LSb') {
if(b == 'VOIP') {a = '01uT0000000zxBPIAY';}
else if(b == 'Radio') {a = '01uT0000000zxC9IAI';}
else {a = '01uT0000000zxC2IAI';}
blineItems.add(new OpportunityLineItem(quantity = o.Product_Quantity__c,
UnitPrice = o.Product_Price__c,
OpportunityId = o.Id,
pricebookentryid = a
));
}
}
insert blineItems;}
And maybe there's a more efficient way to use Case for PriceBookEntryId's: VOIP, Radio etc...
Thanks in advance!
- rumdumdum
- January 27, 2010
- Like
- 0
- Continue reading or reply
Apex Data Loader Account update
Hello,
I'm using the Apex Data Loader (17.0) to load the account table. I have Sys Admin privilege. I can't seem to update the OwnerID field though the data loader to an owner other than myself. No matter what I do, Salesforce sets my ID as the ownerID. I can change it just fine interactively through the wizard to whatever I want, but I can't seem to do it from inside of the Apex Data Loader. The OwnerID value I am using in the Data Loader is the ID field that goes with the user I want. Anyone have any suggestions?
Gloria Lee
- Aeries
- January 23, 2010
- Like
- 0
- Continue reading or reply
Defining filter criteria for a lit in a custom controller
Hi,
I'm trying to extend the filter criteria in this code to show only records whose date field (workshop_date__c) are either today or in the future.
Any ideas on how I edit this code to do that?
listClass = [Select Id, Name, Contact__c,Contact__r.Name, Product2__c,Product2__r.Name, Workshop_Date__c From SFDC_Class__c Where Product2__r.Name = 'Austin CEU Workshop' Limit 1000];
Just to be clear.. this is the code from a custom controller used for a visualforce page displayed publicly with sites.
Thanks for helping out a newb.
- Gregory512
- January 12, 2010
- Like
- 0
- Continue reading or reply
a simple trigger causing exceptions
Hi .. I'm getting Max SOQL queries errors (Too many SOQL queries: 21) from my triggers.
My trigger is this:
trigger trgAccountCalculations on Account (before delete) {
if (trigger.isBefore && trigger.isDelete) {
for (Account a : [Select Id, Name,
(Select Id From Billings__r LIMIT 1)
From Account Where ID IN: trigger.old])
{
if (a.Billings__r.size() > 0)
trigger.oldMap.get(a.Id).addError('ERROR : Cannot delete this Account.');
}
}
}
How do u guys see this trigger to be broken with Governor Limit? I don't think I can bulkify it more :-( ...
- VarunC
- January 12, 2010
- Like
- 0
- Continue reading or reply
Issue using the NetDocuments API - UpdateLookupTable
I am trying to integrate NetDocuments with Salesforce. Specifically, I am trying to pass a CSV formatted string to NetDocuments which will grant certain permissions on NetDocuments. The code with an issue is below:
public String createProjectAndSecurity(String sessionId) { String resultStatus; HttpRequest externalRequest = new HttpRequest(); externalRequest.setMethod('POST'); externalRequest.setEndpoint('https://vault.netvoyage.com/ndApi/storage.asmx'); externalRequest.setHeader('Content-Type', 'text/xml; charset=utf-8'); externalRequest.setHeader('SOAPAction', 'http://netdocuments.com/ndApi/UpdateLookupTable');// externalRequest.setHeader('Cookie', sessionId); String bodyString = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'; bodyString += '<soap:Body>'; bodyString += '<UpdateLookupTable xmlns="http://netdocuments.com/ndApi/">'; bodyString += '<repository>XX-XXXXXXXX</repository>'; bodyString += '<emailAddr>greg@interactiveties.com</emailAddr>'; bodyString += '<completionEmail>True</completionEmail>'; bodyString += '<updateMode>add</updateMode>'; bodyString += '<tableData>Project, Project Type, Project Closed, Project Access, Project Hold\nTESTING - 001,,,XYZ Company|VES,</tableData>'; bodyString += '</UpdateLookupTable>'; bodyString += '</soap:Body>'; bodyString += '</soap:Envelope>'; externalRequest.setBody(bodyString); Http http = new Http(); try { HTTPResponse externalResponse = http.send(externalRequest); resultStatus = externalResponse.getStatus(); } catch(System.CalloutException e) { //Exception handling goes here.... } return resultStatus; }
I keep receiving an internal server error response from NetDocuments. I am able to login to NetDocuments and get a session variable, which is what gets passed to this class and used in the request. I think the problem is with the value being passed in the tableData portion of the request but I am not sure. This tableData value should be a CSV formatted string.
Does anyone have any ideas?
-greg
- Greg H
- September 27, 2012
- Like
- 0
- Continue reading or reply
Deployment Error: ...Not available for deploy for this organization
While trying to deploy code using Ant I receive the error "...not available for deploy for this organization." So I tried to deploy my code using Eclipse but the Classes I want to deploy are not showing up as being able to deploy. Does anyone know what is causing this problem or how to fix it?
-greg
- Greg H
- October 04, 2010
- Like
- 0
- Continue reading or reply
UNSUPPORTED_APEX_TRIGGER_OPERATION
We have a trigger on Task that has been working fine for over a year. Recently, an admin tried to add a number of recurring Tasks via the data loader and received the error message "UNSUPPORTED_APEX_TRIGGER_OPERATION:Apex Task trigger cannot handle batch operations on recurring tasks."
I thought I could update the trigger to check for recurring tasks but that still doesn't resolve the problem. Has anyone come across this error and, if so, how did you resolve it?
-greg
- Greg H
- January 13, 2010
- Like
- 0
- Continue reading or reply
Account Trigger Fires Partially When Owner Is Changed in UI
I wrote a trigger to fire on the Account object after the record is updated. At a high level I want the trigger to reassign Contacts and Opportunities to the new Account Owner but only when a specific User makes the update.
Upon testing in the user interface, I found that the trigger fires when a User reassigns an Account using the "[Change]" link on the Account detail page even when the User is not the one specified in the trigger.
Am I missing something about how an Account trigger works regarding OwnerId updates?
-greg
- Greg H
- December 08, 2009
- Like
- 0
- Continue reading or reply
Estimate for Migrating Application from sControl/AJAX Toolkit to Visualforce
I am looking to move an old AppExchange product from its current technology (sControl/AJAX toolkit) to Visualforce. The high level business requirement is to have the product function and look exactly as it does today. Please use this link to access an org where the product is installed and functioning so that you can research my request and provide an adequate estimate. Interested parties can contact me by phone (303) 317-2235 or email sales@interactiveties.com.
-greg
- Greg H
- August 05, 2009
- Like
- 0
- Continue reading or reply
Controller To Pass Data From More Than One Object?
I have an existing Visualforce page with a custom controller. When the code was originally written all of the data for display on the VF page was available via relationships and it was simple to gather in a single query. Business requirements have now changed and I need to get data from another object based on results from the original query. How do I combine two different query results into a single List?
My over-simplified, original code is below:
--- Visualforce Page --- <apex:page controller="cController"> <apex:pageBlockTable value="{!Data}" var="d"> <apex:column>{!d.Field_1__c}</apex:column> <apex:column>{!d.Field_2__c}</apex:column> </apex:pageBlockTable> </apex:page> --- Custom Controller --- public class cController { public Custom__c[] co = new List<Custom__c>(); public cController() { try { co = [SELECT Account__c, Field_1__c, Field_2__c FROM Custom__c]; } catch (Exception e) { //System.Debug('Exception: '+e); } } public Custom__c[] getData() { return co; } }
For lack of a better way to explain what I would like to do - here is some incorrect code:
public class cController { public sObject[] co = new List<sObject>(); public cController() { try { for (Custom__c temp : [SELECT Account__c, Field_1__c, Field_2__c FROM Custom__c]) { Contact cont = [SELECT Name FROM Contact WHERE AccountId = :temp.Account__c LIMIT 1]; co.add(temp, cont); } } catch (Exception e) { //System.Debug('Exception: '+e); } } public sObject[] getData() { return co; } }
Basically, I simply want the controller to pass back data from more than one object so I can display it together on the page. I thought I could use the generic sObject but that is proving difficult and I am not familiar with nested Lists (if that is even an option).
Any assistance would be greatly appreciated,
-greg
- Greg H
- March 20, 2009
- Like
- 0
- Continue reading or reply
Do Managed Packages Count Against Org Limits?
I have been looking through documentation but haven't found an answer yet. If an org is maxed out on custom objects and they would like to install a package, which includes two objects, would the installation error out or would the installation be permitted?
-greg
- Greg H
- February 20, 2009
- Like
- 0
- Continue reading or reply
Using <apex:attribute> from a Custom Component in the Controller's Query
I have a visualforce page that uses a custom component. I want the component's controller to be aware of a variable that should be used in the the WHERE clause of the controller's query. My code is below:
<!-- visualforce page -->
<apex:page controller="pageController" standardStylesheets="true" tabStyle="SObject__c">
<apex:repeat value="{!categories}" var="c">
<c:customComponent cName="{!c.Name}" cRef="{!c.Id}"></c:customComponent>
</apex:repeat>
</apex:page>
<!-- custom component -->
<apex:component controller="componentController">
<apex:attribute name="cName" description="desc..." type="String" required="true"></apex:attribute>
<apex:attribute name="cRef" description="String to use for controller class." type="String" required="true" assignTo="{!value}"></apex:attribute>
<div class="customStyle">
<apex:dataTable id="linkList" value="{!links}" var="link">
<apex:column>
<apex:facet name="header">Field 1</apex:facet>
<apex:outputText value="{!link.Field_1__c}"></apex:outputText>
</apex:column>
<apex:column>
<apex:facet name="header">Field 2</apex:facet>
<apex:outputText value="{!link.Field_2__c}"></apex:outputText>
</apex:column>
</apex:dataTable>
</div>
</apex:component>
<!-- component controller -->
public with sharing class componentController {
public SObject__c[] links = new List<SObject__c>();
String value;
public String getValue() {
return value;
}
public void setValue(String s) {
value = s;
}
public componentController() {
try {
links = Database.query('SELECT Field_1__c, Field_2__c FROM SObject__c WHERE Field_3__c=:value');
} catch (Exception e) {
System.Debug('Exception: '+e);
}
}
public SObject__c[] getLinks() {
return links;
}
}
Basically, the "cRef" attribute from the component does get assigned to the "value" variable in the componentController but "value" is actually NULL when the query inside the componentController is executed.
Can anyone point out what my code is missing in order to use the "value" from the component in the query?
Any help is greatly appreciated,
-greg
- Greg H
- February 20, 2009
- Like
- 0
- Continue reading or reply
VF page Inside Home Page Component
- Greg H
- February 06, 2009
- Like
- 0
- Continue reading or reply
Possible Bug with Summer 08?
trigger PushEmployees2AccountProductLine on Account (before update) { Map<Id, Account> acctsWithNewEmplCnt = new Map<Id, Account>(); for (Integer i = 0; i < Trigger.new.size(); i++) { if(Trigger.old[i].NumberOfEmployees != Trigger.new[i].NumberOfEmployees){ acctsWithNewEmplCnt.put(Trigger.old[i].id, Trigger.new[i]); } } List<Account_Product_Line__c> updatedAPL = new List<Account_Product_Line__c>(); for (Account_Product_Line__c apl : [SELECT id, Account__c, Employees_Here__c FROM Account_Product_Line__c WHERE account__c in :acctsWithNewEmplCnt.keySet()]) { Account parentAccount = acctsWithNewEmplCnt.get(apl.account__c); apl.Employees_Here__c = parentAccount.NumberOfEmployees; updatedAPL.add(apl); } update updatedAPL; }
I am not sure if the problem is in the trigger we wrote or if there is a possible bug in the summer release. Does anyone have any ideas?
- Greg H
- May 29, 2008
- Like
- 0
- Continue reading or reply
Pattern for a credit card number?
- Greg H
- May 19, 2008
- Like
- 0
- Continue reading or reply
System.Exception: Too many query rows
global class getOppSummary2 { webService static Opportunity[] getOpps(String regionVal, Date startDate, Date endDate, Date lastNinetyDays) { Map<Id, User> allUsers = new Map<Id, User>(); for (User[] usrArray : [SELECT Id FROM User WHERE Reporting_Region__c = :regionVal AND IsActive = true]) { for (Integer a = 0; a < usrArray.size(); a++) { allUsers.put(usrArray[a].id,usrArray[a]); } } Opportunity[] allOpps = new Opportunity[]{}; for (Opportunity oppArray : [SELECT AccountId,Account.Name,Amount,CloseDate,CreatedById,CreatedBy.Username,First_Appointment_Date__c,Id,MFTC_DUNS_Number__c,Name,OwnerId,Owner.FirstName,Owner.LastName,RecordTypeId,Revenue_Type__c,StageName FROM Opportunity WHERE OwnerId in :allUsers.keySet() AND ((IsClosed=false AND CloseDate < :startDate AND StageName<>'Targeted Account (No Forecasted Sale)') OR (IsClosed=true AND (CloseDate >= :lastNinetyDays AND CloseDate <= :startDate) AND (StageName='Closed Won' OR StageName='Closed Won/Contract')) OR (IsClosed<>true AND (StageName='Targeted Account (No Forecasted Sale)' OR StageName='Fallback Opportunity')) OR (IsClosed<>true AND (CloseDate >= :startDate AND CloseDate <= :endDate) AND (StageName='First Time Visit Completed' OR StageName='Proposal/Pricing Presented' OR StageName='Verbal Agreement' OR StageName='First Order')))]) { allOpps.add(oppArray); } return allOpps; } static testMethod void getOppSummaryTest() { getOpps('West',Date.newInstance(2008,03,12),Date.newInstance(2008,06,12),Date.newInstance(2007,12,31)); } }
My question is why am I encountering this exception? Am I not looping through the map correctly? I have over 4,000 users and way more opportunities to churn through which is why I want to do this in a class.
- Greg H
- March 12, 2008
- Like
- 0
- Continue reading or reply
Error with Deployment - Invalid version specified:12.0
*** Deployment Log *** Result: FAILED ... # Deploy Results: Name: unpackaged/package.xml Action: NO ACTION Result: FAILED Problem: Invalid version specified:12.0
Does anyone know why this is happening? Could it be because our Sandbox was already upgraded to the Spring 08 (API version 12.0) release and our production instance wasn't yet (still API version 11.1)?
- Greg H
- January 30, 2008
- Like
- 0
- Continue reading or reply
Tab Override Bug: Read-Only Profiles
- Greg H
- December 13, 2007
- Like
- 0
- Continue reading or reply
Movement of Apex Code from Developer Edition to Other Editions
- Greg H
- October 03, 2007
- Like
- 0
- Continue reading or reply
Image Missing in Header
<apex:page tabStyle="Custom__c">
When I use "Contact" or "Account" the icon for those objects gets displayed.
- Greg H
- September 21, 2007
- Like
- 0
- Continue reading or reply
Status Code of Remote Server
function getResponse() { sforce.connection.remoteFunction({ url : "http://remote.location.com/specific/page", method : "GET", mimeType : "text/xml", onSuccess : function(response) { document.getElementById("responseTXT").innerHTML = "<div style=\"font-weight: bold; color: #FF0000;\">SUCCESS!!!!</div><div>"+response+"</div>"; }, onFailure : function(response) { document.getElementById("responseTXT").innerHTML = "<div style=\"font-weight: bold; color: #FF0000;\">Failed:</div><div>"+response+"</div>"; } }); }
If you look at my function from above, you can see that I can get back "response" and when it does return it literally displays the content of the remote URL in the sControl. But I was hoping I'd be able to get back something like "response.status" or "response.statusCode" and simply use that code to determine if I should allow for the POST later in the sControl.
- Greg H
- August 09, 2007
- Like
- 0
- Continue reading or reply
ProfileId on User object
- Greg H
- March 27, 2007
- Like
- 0
- Continue reading or reply
Profiles with Specific Opportunity RecordType
- Greg H
- February 20, 2007
- Like
- 0
- Continue reading or reply
Picklist Value Translation in Meta Data
- Greg H
- February 15, 2007
- Like
- 0
- Continue reading or reply
Having trouble referencing Account object in trigger. Code fails "Fatally"
// the line below fails;
Account a;
}
- Admin User 9581
- September 25, 2019
- Like
- 0
- Continue reading or reply
Issues with test class coverage (62%)
I have a simple trigger and test class where I need some help to get from the 62% coverage and up to at least 90%. The lines which are not covered are the ones after the 'IF' statement.
Can someone please help me with the remaining test class code?
The trigger is as follows:
trigger contactCreateCommunityUser on Contact (before insert) {
String currentuser = UserInfo.getUserId();
String emailAddress = UserInfo.getUserEmail();
ID contactId = [Select contactid from User where id =: Userinfo.getUserid()].contactId;
List <User> systemAdm = [SELECT Id
FROM User
WHERE Name like '%Systemadministrator%'];
system.debug('Systemadmin ID ' + systemAdm);
If(contactId != null) {
ID AccID = [Select AccountID from Contact where id =: contactid].AccountId;
for(Contact con : trigger.new){
con.OwnerId = systemAdm.get(0).Id;
}
}
}
Test class:
@isTest
private class contactCreateCommunityUserTest {
static testmethod void contactCreateCommunity() {
Account acc = [SELECT Id
FROM Account
Limit 1];
Contact con = new contact();
con.lastName = 'TestLastName';
con.AccountId = acc.Id;
Insert con;
}
}
- Øyvind Borgersen 10
- September 25, 2019
- Like
- 0
- Continue reading or reply
Referencing sObject within another sObject
I'm in the process of trying to consolidate the SOQL calls within a trigger of a particularly difficult sObject. This sObject has enough code running on it that we're pretty regularly hitting the 101 error--so it's time to clean up and bulkify where possible.
I've run the following to fill a map with an sobject, and the children of that sobject. Let's assume for the moment that Service_Order_Line is a child of Service_Order with a many-to-one relationship, and I've filtered this down so I'm only getting one Service_Order and maybe 5 or 10 Service_Order_Lines:
map<ID, Service_Order__c> testResults = new map<ID, Service_Order__c>([select ID, Name, (select ID, Name from Service_Order_Line__r) from Service_Order__c']);
Further down in the trigger, I'll need to reference the child objects, but I can't seem to find a syntax to make it work. How would I write the following to loop through the children of testResults?
for(Service_Order_Line childrenOfTestResults : testResults.Service_Order_Line__r) {
system.debug(childrenOfTestResults.Name);
}
- Jared Rosenberg
- September 24, 2019
- Like
- 0
- Continue reading or reply
Do Apex Callouts count against API Limits
I know they are limited by Governor limits but do they count against the org API Limits.
The salesforce documentation is not very clear and not sure how to get official confirmation from Salesforce on this.
http://resources.docs.salesforce.com/200/9/en-us/sfdc/pdf/salesforce_app_limits_cheatsheet.pdf. Page 41 of the document (page 37 based on Numbering in the document) clearly says Apex callouts are excluded.
But the latest document link does not have such Note
https://resources.docs.salesforce.com/222/latest/en-us/sfdc/pdf/salesforce_app_limits_cheatsheet.pdf (No Note at Page 9)
- Viswanathan Gajendiran
- September 23, 2019
- Like
- 0
- Continue reading or reply
Dereference an Object from trigger
trigger UpdateErrorLog on Error_Log__c (before insert) {...}
Again the above trigger was deactivated thru change set but I cannot delete the Error_Log__C. I submitted a case to Salesforce and directed me to here. How can I dereference Error_Log__c from UpdateErrorLog trigger?
- Takashi Koyama 14
- September 23, 2019
- Like
- 0
- Continue reading or reply
simulation of code in Salesforce for a request in Postman
I exeucte a postman request to get the token.
I was writing a code for authenticating the API in slaesforce, but found that the headers are not correct.
I tried to get the headers by other way.
How can i write the code for first part of the screen shot, ?
- Ab
- September 23, 2019
- Like
- 0
- Continue reading or reply
How to check if an email contains the right format
if(email__c.contains('@gmail.com'){} but then I realized that this may not be enough because someone could potentially enter an email of gmail.com@hotmail.com for example. So I want to see what I can write in apex to check if the email is in the format ###@gmail.com
Thank you
- Afzaal Hassan
- August 28, 2019
- Like
- 0
- Continue reading or reply
error while trying to authenticate with salesforce SOQL App
Hello,
I am trying to create new authetication through my application and I am getting {"error":"invalid_grant","error_description":"authentication failure"} error when trying to call the Token Request: "https://eu5.salesforce.com/services/oauth2/token"
Can u help me out why I'm getting this error ?
Best Regards ,
Raneen Khoury
- Raneen Khoury
- August 19, 2019
- Like
- 0
- Continue reading or reply
Error when using a second soql query in apex class
Class: global class EmailPTRAttWearplates implements Messaging.InboundEmailHandler { global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) { Messaging.InboundEmailResult result = new Messaging.InboundEmailresult(); Production_Tracking_Record__c ptr; Product2 prod; ptr = [select id, Product__c from Production_Tracking_Record__c where Name = :email.subject]; prod = [select Wearplate__c, Wearplate_Thickness__c, Pre_Order_Wearplates__c from Product2 where Name = :ptr.Product__c]; if(prod.Pre_Order_Wearplates__c=false) { PTR_Attachment__c Att = new PTR_Attachment__c(Name=email.subject, PTR__c=ptr.Id, Component__c='Wearplate', Quantity__c=2, Thickness__c=prod.Wearplate_Thickness__c, Material__c=prod.Wearplate__c, Directory_Link_Text__c='R:\\Parts Orders\\Internal Laser Parts'); insert Att; } return result; } } Test Class: @IsTest public class EmailPTRAttWearplates_Test { public static list<Production_Tracking_Record__c> PTRlist; static testMethod void myTest() { Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope env = new Messaging.InboundEnvelope(); email.fromAddress = 'test@test.com'; email.subject = '12345'; Test.startTest(); Account acct = new Account(Name='Test Account', Type='Direct Customer', Shipping__c='Prepaid', Ship_Via__c='UTS', Sales_Discount__c=0); insert acct; Product2 prod = new Product2(Name='Test Product', Rotor_Configuration__c='Closed Adjustable', Inboard_or_Outboard__c='Outboard', Endcap_Face_Preparation__c='Wearplate', Wearplate__c='Mild Steel', Wearplate_Thickness__c='.375', Pre_Order_Wearplates__c=false, Vane_Thickness__c='.375', Vane_Material__c='AR500', Shroud_Mat__c='Mild Steel', Shroud_Thickness__c='.375', Adjustable_Blade_Thickness__c='0.3125', Blade_Mat__c='Mild Steel'); insert prod; Opportunity opp = new Opportunity(Name='12345', RA__c='12345', StageName='Quote Sent', CloseDate=System.today(), AccountId=acct.Id, Make__c='Kice', Model__c='VJ 14x10x10', Product__c=prod.Id, Max_Temp__c='120', Serial__c='N/A', Cold_Clr_Radial__c='.004-.007', Cold_Clr_Side__c='.004-.007'); insert opp; Production_Tracking_Record__c ptr = new Production_Tracking_Record__c(Name = '12345', RA__c = opp.Id, Product__c = prod.Id); insert ptr; EmailPTRAttWearplates paw = new EmailPTRAttWearplates(); Messaging.InboundEmailResult result = paw.handleInboundEmail(email, env); Test.stopTest(); System.assert (result.success, 'InboundEmailResult returned a failure message'); } }
- Cody Sanders 33
- August 13, 2019
- Like
- 0
- Continue reading or reply
A developer needs to create an audit trail for records that are sent to the recycle bin. Which type of trigger is most appropriate to create?
before delete
after delete
before undelete
- Kristiana Granger
- August 13, 2019
- Like
- 0
- Continue reading or reply
Having a problem getting a salesforce access token. I've got a post man call that works fine, but it's not working in code
I've tried to doing the equivlent to what I was doing in postman but I'm not sure if getting this right.
var client = new HttpClient(); string baseAddress = @"https://test.salesforce.com/services/oauth2/token"; string grant_type = "authorization_code"; string client_id = "client_id here"; string client_secret = "client_secret here"; string auth_url = "https://test.salesforce.com/services/oauth2/authorize"; string callback_url = "https://app.getpostman.com/oauth2/callback"; string redirect_uri = "https://app.getpostman.com/oauth2/callback"; var form = new Dictionary<string, string> { {"grant_type", grant_type}, {"client_id", client_id}, {"client_secret", client_secret}, {"auth_url", auth_url}, {"callback_url", callback_url}, {"redirect_uri", redirect_uri} }; HttpResponseMessage tokenResponse = client.PostAsync(baseAddress, new FormUrlEncodedContent(form)).GetAwaiter().GetResult(); var jsonContent = tokenResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult();
This is the error I'm getting:
{ "error": "invalid_grant", "error_description":"invalid authorization code" }
- Tew Wer
- August 13, 2019
- Like
- 1
- Continue reading or reply
Rookie Trigger
I discovered geocodes could be added to Accounts without needing code but for the sake of learning, could someone provide a newbie with constructive feedback on this trigger? I'd really like to figure this out.
I have two sales reps splitting California for their sales territory. One owns anything above Santa Barbara and one owns everything else. I created a custom object labeled 'Cities' with fields for City__c and Latitude__c, and imported this data for all California cities.
Whenever an Account is created or updated, I want my trigger to query the custom object 'Cities', match the Account BillingCity to the City__c field on my custom object, and evaluate if the corresponding Latitude__c field on my custom object is greater than Santa Barbara's latitude.
If the latitude is greater than Santa Barbara's, add the Account to a list which will be updated with the Northern Sales Rep as the Owner. If the latitude is not greater than Santa Barbara's, add the Account to a list which will be updated with the Southern Sales Rep as the Owner.
When I test the trigger, I get the dreaded "System.NullPointerException: Attempt to de-reference a null object ()" error which confuses me because I check to see if BillingCity is null and confirmed I have all California cities and latitudes imported into my custom object. I have a feeling the error is somewhere around line 13 where I query my custom object and try to find the corresponding latitude...
Thanks to anyone for taking the time to help me learn!
Here is my trigger:
trigger CaliSalesTerritory on Account (before insert, before update) { List <Account> caliAccts; // A List to hold all California Accounts List <Account> norCalCities; // A List to hold all Northern California Accounts List <Account> soCalCities; // A List to hold all Southern California Accounts for (Account acct : Trigger.new) { if (acct.BillingState == 'California' && acct.BillingCity != null) { caliAccts.add(acct); // For all Accounts being inserted or updated, if the BillingState is "California" and the BillingCity isn't null, add the Account to the caliAccts list } } for (Account acct2 : caliAccts) { Cities__c caliLatitude = [Select Latitude__c FROM Cities__c WHERE City__c = :acct2.BillingCity]; // For all Accounts in the caliAccts list, query the Cities__c object and return the Latitude based on the Account's BillingCity if (caliLatitude.Latitude__c > 34.4285) { norCalCities.add(acct2); // If the Latitude is greater than Santa Barbara's latitude, add the Account to the norCalCities list } else { soCalCities.add(acct2); // If the Latitude is not greater than Santa Barbara's latitude, add the Account to the soCalCities list } } for (Account northRepAcct : norCalCities) { northRepAcct.OwnerId = '0050f0000097wqI'; //Northern Sales Rep UserId // Assign all Accounts in the norCalCities list to the Northern Sales Rep } update norCalCities; for (Account southRepAcct : soCalCities) { southRepAcct.OwnerId = '0050f000009K2kr'; //Souther Sales Rep UserId // Assign all Accounts in the soCalCities list to Southern Sales Rep } update soCalCities; }
- Rookie Developer
- August 13, 2019
- Like
- 0
- Continue reading or reply
Fetch value from nested list
can anyone pls suggest how to get a certain value from nested list<map's>
List<Map<String,Object>> newl = new List<Map<String,Object>>();
for(Object itrObj : l){
newl.add((Map<String, Object>)itrObj); // got all records here
//how to get certain values from the collection
system.debug('id val==>'+ newl);
}
- roni shore
- August 13, 2019
- Like
- 0
- Continue reading or reply
Generate a PDF document
I would really need your help. :(
I need to generate for my organization a PDF document (Order Insertion for our advertising campaigns). I would need to add different fields that the SF users could fill in, like: Campaign Name: xxxx , Campaign Start Date: xx/xxx/xxxx, Price: xx/CPM, etc.
Also, I need to add a header (picture- logo of the company) and a footer (contact, signature, etc).
Basically, I have the Order Insertion in a .xlsx format and I would like to transfer all the info from the Excel in Salesforce. As I understood, it could work with VisualPage creation and customization but I think I need some programmatic help.
Thank you very much for your answer,
Otilia
- Otilia Strait
- August 13, 2019
- Like
- 0
- Continue reading or reply
Limits on Batch Apex with Trigger: Will it be 5 or 105?
I'm new to developing and trying to determine if I will get errors thrown in my batch apex code. The purpose is to: upon deactivation of a user (trigger, which I understand isn't best practice but don't know another way the batch can be automatically started w/o checking for deactivated users every night), all of the leads of deactivated user are queried to change the OwnerId to a catchall user. The trick is that one user may have as many as 200,000 leads that need to be updated, hence why I am using batch apex. Two questions:
1. How many batch jobs will be activated with each deactivated user? (I think the answer is one?)
2. Will the batch job be sent to the Flex Queue as 'holding' and then to active, giving the org 105 possible batch jobs to be held/processed at once before throwing errors, or will it bypass Flex Queue, thereby limiting the org to only 5 batch jobs at a time?
I hope my questions make sense, and I appreciate any help. I have spent many hours researching this as a newbie. In case it's relevant, my code is below:
Trigger:
trigger BatchUpdateTrigger2 on User (after update) { //Map will keep deactivated users and their Id's, to be used later in batch Apex Map<id, User> DeactivatedUsers = new Map<id, User>(); //Check all users in trigger, first if the IsActive button has been newly changed and if it now says that the user is not active for (Integer i=0;i<Trigger.new.size();i++) { if (Trigger.new[i].IsActive!=Trigger.old[i].IsActive && Trigger.new[i].IsActive == false) { DeactivatedUsers.put(Trigger.new[i].Id, Trigger.new[i]); } } // Make sure that there are users to be processed if (DeactivatedUsers.size() > 0) { BatchUpdateLeads objBatchUpdateLeads=new BatchUpdateLeads(DeactivatedUsers); Database.executeBatch(objBatchUpdateLeads); } }
Batch Apex Class:
global class BatchUpdateLeads implements Database.Batchable<SObject> { //Save a public variable to hard-code the catchall user that will become lead owner public Id GenericUserId = '0054P000009pLkrQAE'; //map of userid - user that retrieves deactivated user(s) from previous trigger Map<Id, User> DeactivatedUsersMap = new Map<Id, User>(); global BatchUpdateLeads(Map<Id, User> DeactivatedUsers) { DeactivatedUsersMap = DeactivatedUsers; } //Search for the leads whose OwnerId is the deactivated user(s) global Database.QueryLocator start(Database.BatchableContext BC) { return DataBase.getQueryLocator([SELECT Id, OwnerId FROM Lead WHERE OwnerId IN : DeactivatedUsersMap.keySet()]); } //For leads whose owner was deactivated, change OwnerId to the catchall user global void execute(Database.BatchableContext BC, List<sObject> scope){ List<Lead> leads = (List<lead>)scope; for (Lead l: leads){ l.OwnerId = GenericUserId;} //Check that there are leads to be updated, then update if (leads.size() > 0){ update leads; } } global void finish(Database.BatchableContext BC) { //Send an email to system admin after the batch completes (fill in email) Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {'xxxxxxx@gmail.com'}; mail.setToAddresses(toAddresses); mail.setSubject('Apex Batch Job is done'); mail.setPlainTextBody('The Batch Apex Job Processed Successfully'); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } }
- Sierra VP
- August 12, 2019
- Like
- 0
- Continue reading or reply
Need help with Contact/Event trigger
Event 1: tied to Contact A & Contact B; sales_within_1_year = $0
Event 2: tied to Contact A & Contact C; sales_within_1_year = $10
Contact A sales changes from $100 to $200.
Event 1: new sales_within_1_year = $100
Event 2: new sales_within_1_year = $110
If the sales for Contact B or C changed, it would only affect the event they are tied to.
I thought my trigger would work, and it does when I change a contact's sales number individually. But when I bulk update contacts, none of the sales_within_1_year numbers change. I was wondering if someone could help me through this. Thanks!
Here is my trigger:
trigger EventSales on Contact (before update) {
//Create a list of contact IDs that have updating sales
List<Id> contactIds = new List<Id>();
for(Contact con : trigger.new) {
if(Trigger.newMap.get(con.Id).Sales__c == NULL) return;
else if(trigger.newMap.get(con.Id).Sales__c == 0) return;
else if(trigger.oldMap.get(con.Id).Sales__c == NULL) {
contactIds.add(con.Id);
}
else if(trigger.newMap.get(con.Id).Sales__c !=
trigger.oldMap.get(con.Id).Sales__c) {
contactIds.add(con.Id);
}
}
//Create a list of event relations (contact-event pairs) for updating contacts
List<EventRelation> evRel = [SELECT EventId, RelationId
FROM EventRelation
WHERE RelationId IN :contactIds];
//Create a map of the updating contacts and their related events
Map<Id, List<Id>> contactEvents = new Map<Id, List<Id>>();
//Create a list of event Ids that are going to be updated
List<Id> eventIds = new List<Id>();
//Put the contact Id and event Id in the map for events that have updating contacts
for(EventRelation rel :evRel) {
if(contactEvents.containsKey(rel.RelationId)) {//If the contact is already in the map
List<Id> relatedEv = contactEvents.get(rel.RelationId);//Grab the list of events tied to the contact
relatedEv.add(rel.EventId);//Add the new event to the list
contactEvents.put(rel.RelationId, relatedEv);//Put the updated list into the map
}
else {//If the contact isn't in the map
contactEvents.put(rel.RelationId, new List<Id>{rel.EventId});//Put the contact and event into the map
}
//Add the updating event to the eventIds list
if(eventIds.contains(rel.EventId)) return;
else eventIds.add(rel.EventId);
}
//Create a list of events that are going to be updated
List<Event> listEventsMaker = [SELECT Id, Sales_within_1_year__c
FROM Event
WHERE Id IN :eventIds
AND EndDateTime = LAST_N_DAYS:365];
List<Event> listEvents = new List<Event>();
for(Event ev :listEventsMaker) {
if(listEvents.contains(ev)) return;
else listEvents.add(ev);
}
//Keep a list of events to update
List<Event> changedEvents = new List<Event>();
//Update the sales amounts for the events
for(Id con :contactEvents.keySet()) {//For each contact in the map
List<Id> thisContact = new List<Id>();//Create a list of events tied to this specific contact
Contact oldCon = trigger.oldMap.get(con); //create a record for the contact pre-update
Contact newCon = trigger.newMap.get(con); //create a record for the contact post-update
if(newCon.Sales__c == NULL) return;
else if(newCon.Sales__c == 0) return;
else if(oldCon.Sales__c == NULL) {
for(Id event :contactEvents.get(con)) {
thisContact.add(event);
}
for(Event ev :listEventsMaker) {
if(thisContact.contains(ev.Id)) {
changedEvents.add(ev);
if(ev.Sales_within_1_Year__c == NULL) {
ev.Sales_within_1_Year__c = newCon.Sales__c;
}
else ev.Sales_within_1_Year__c += newCon.Sales__c;
}
}
}
else if(oldCon.Sales__c
!= newCon.Sales__c) {
for(Id event :contactEvents.get(con)) {
thisContact.add(event);
}
for(Event ev :listEventsMaker) {
if(thisContact.contains(ev.Id)) {
changedEvents.add(ev);
if(ev.Sales_within_1_Year__c == NULL) {
ev.Sales_within_1_year__c = (newCon.Sales__c
- oldCon.Sales__c);
}
else ev.Sales_within_1_Year__c += (newCon.Sales__c
- oldCon.Sales__c);
}
}
}
}
update changedEvents;
}
- Mitch Morrison
- August 12, 2019
- Like
- 0
- Continue reading or reply
APEX class to Parse email body to update fields on multiple contact records or Parse data in an attachment
- Spencer Widman
- August 05, 2019
- Like
- 0
- Continue reading or reply