-
ChatterFeed
-
11Best Answers
-
3Likes Received
-
0Likes Given
-
40Questions
-
111Replies
Validation Rules, make fields not mandatory if value to other field iis Opportunity Lost?
OR(
$Profile.Name ="2F00eb0000000YhB7",
$Profile.Name ="2F00e9E000000ae9h",
$Profile.Name ="2F00eb0000000YhB1",
ISBLANK(NextStep),
ISBLANK( Next_Step_By__c ),)
but I'd like to add a condition: when the opportunity is Lost, these fields are no longer mandatory.
I tried to add this but it doesn’t work
AND(ISPICKVAL( StageName ,"Opportunity Lost"),NOT (ISBLANK( NextStep))),
Do you have any idea ?
- chris lim 15
- July 05, 2023
- Like
- 0
- Continue reading or reply
One user can't create ContentVersion
We have a script that does a HTTP callout to create a PDF, the callback saves this PDF in Salesforce as a document.
We have this working for multiple objects and this works fine. But for one type, one user, has an error that we can't seem to resolve.
The user is a System admin, other system admins can run it without issues, even profiles with less rights (sales user) can run it without issue.
But whenever this user runs it, he gets this error that we don't understand:
System.DmlException: Insert failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, common.exception.SqlNoDataFoundException: ERROR: query returned no rows Where: PL/sdb function doc.contentfolders.get_root_fdr_details(character varying) line 16 (SFSQL 286) at SQL statement SQLException while executing plsql statement: {?=call ContentFolders.get_root_fdr_details(?)}(07H09000000D1Dj) SQLState: P0002 Where: PL/sdb function doc.contentfolders.get_root_fdr_details(character varying) line 16 (SFSQL 286) at SQL statement File: plsdb_exec.c, Routine: exec_stmt_execsql_body, Line: 3307 [conn=STANDARD:1:1:108918:1]: [] Class.HttpCallout.processContract: line 77, column 1the code it fails on is this:
Callout calloutObj = (Callout)JSON.deserialize(calloutString, Callout.class); HttpRequest req = setupHttpRequest(calloutObj); HttpResponse res = makeRequest(req); Quote q = [SELECT Name FROM Quote WHERE Id= :recordId LIMIT 1]; ContentVersion conver = new ContentVersion(); conver.ContentLocation = 'S'; conver.PathOnClient = 'Contract.pdf'; conver.Title = 'Contract_' + q.Name; conver.VersionData = res.getBodyAsBlob(); conver.Type__c = 'Contract'; insert conver; <=== Line 77
As I said, works fine for everyone, but this one specific user we get this error.
Anyone an idea how to fix this? We don't even understand the error completely...
- Nick Verschueren
- February 20, 2023
- Like
- 0
- Continue reading or reply
link task and lead
I am trying to find a way to link a field from a Lead object into a Task object. We have setup timezones for out Leads, and we would like the system to automatically populate into the Tasks, so that our employees know the relative time of our clients when looking at their tasks for today.
When I look in object manager, I dod not see a method of adding a formula or reference from Lead to Task, and a recent support engineer mentioned to ask here, as this may be an impossible request. We have an option to have the Time Zone appear for Tasks, but there is no reference to pull in data, so it is always empty.
Any suggestions or clarifications on the limitations would be appreciated.
- Matthew O'Keefe
- January 06, 2023
- Like
- 0
- Continue reading or reply
Batch Apex update issue
I need to update
1.account rating as client customer if opportunity = last 2 years & closed opportunity
2.account rating as prospect if opportunity = last 3 to 5 years & open opportunity.
3. for last 2 years if account have two opportunity and both are open it should get update as prospect.
4.some accounts have two opportunities one as open and another as closed and its updating it as prospect if it has open opportunity for recent year it should get update as client customer
can anyone guide me .
global class AccountOptyBatchclass implements Database.Batchable<sObject> {
global Database.QueryLocator start(Database.BatchableContext bc) {
list<Id> accopty = new list<Id>();
string query='select ID,Name,Rating,(select Id,AccountId,stageName,CloseDate From Opportunities) from Account';
return Database.getQueryLocator(query);
}
global Void execute(Database.BatchableContext bc, List<Account> Scope){
list<Account> accopty = new list<account>();
system.debug('query'+scope);
for(Account a :Scope){
for(Opportunity o: a.Opportunities){
date dt = system.today().adddays(-1825);
date ty = system.today().adddays(-730);
system.debug ('dt'+dt);
system.debug ('ty'+ty);
if((o.CloseDate >=ty) && (o.StageName =='Won-Work In Progress' || o.StageName =='Closed Won' || o.StageName =='Delivered')) {
a.rating='Client - Customer';
accopty.add(a) ;
system.debug(' Last2yearsCloseDate'+a.rating) ;
}
else if( (o.CloseDate >=ty) && (o.StageName =='Shaping' || o.StageName =='Proposal Submitted' || o.StageName =='Decision' || o.StageName =='Engagement' )){
//if ((o.StageName !='Won-Work In Progress' || o.StageName !='Closed Won' || o.StageName !='Delivered' )&&(o.CloseDate < ty)){
a.rating='prospect';
accopty.add(a) ;
system.debug(' Last3to5yearsCloseDate'+a.rating) ; //}
}
}}
update accopty ;
}
global void finish(Database.BatchableContext bc){
}
}
Thanks in Advance
- suji srinivasan
- December 14, 2022
- Like
- 0
- Continue reading or reply
How to solve Test Class covering issue?
I have a Test Class issue can anyone tell me the mistake. I have custom filed "ClinicCode" in the Lead object. I am not passing the code in the test class but the lead is stored under the "leadsWithClinicsList" list. It should be in "leadsWithOutClinicsList"
- Sandeep TechAffinity
- April 07, 2022
- Like
- 0
- Continue reading or reply
test coverage for email attachments
global class DSSEmailHandler implements Messaging.InboundEmailHandler { global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) { Messaging.InboundEmailResult result = new Messaging.InboundEmailresult(); if(email.subject.contains('ref')) { try { Case c = new Case(); c.ContactId = email.fromAddress; c.recordTypeId = '0121O000001WL0u'; c.OwnerId = '00G1O000004lFB4'; c.Description = email.plainTextbody; c.Subject = email.subject; insert c; //to save attachment to case for(Messaging.Inboundemail.BinaryAttachment bAttachment: email.binaryAttachments) { Attachment attachment = new Attachment(); attachment.Name = bAttachment.fileName; attachment.Body = bAttachment.body; attachment.ParentId = c.Id; insert attachment; } result.success = true; }catch (Exception e){ result.success = false; result.message = 'Oops, I failed.' + e.getMessage(); } return result; } return null; } }Here's the test code
@isTest private class DSSEmailHandlerTest { public static Blob createAttachmentBody(){ String body = 'XXXXXXXXXXXXX'; return Blob.valueof(body); } public static testMethod void testmyHandlerTest() { Case c = new Case(); insert c; //String cName = [SELECT Name FROM Case WHERE Id = :c.Id LIMIT 1].Name; Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope env = new Messaging.InboundEnvelope(); email.subject = 'ref'; email.plainTextBody = 'test body'; DSSEmailHandler m = new DSSEmailHandler(); m.handleInboundEmail(email,env); // attachment insert Attachment att = new Attachment(Name = 'XXXXXXXX', Body = Blob.valueof('XXXXXXXXXXXXXX'), ParentId = c.Id); insert att; } }
I can't get this part covered, I'm at 70% without it
Attachment attachment = new Attachment(); attachment.Name = bAttachment.fileName; attachment.Body = bAttachment.body; attachment.ParentId = c.Id; insert attachment; } result.success = true;
- Staci
- February 16, 2022
- Like
- 0
- Continue reading or reply
How can we call a future method from a batch class?
On the other hand, we also want to call this method from Batch class. But Salesforce doesn't allow us to send future method from a batch class?
Any ideas?
- Alper Ozdamar
- June 22, 2020
- Like
- 0
- Continue reading or reply
Apex Interview Question
I was asked this interview question (I am new to Salesforce hence I fubbed the Interview :-( , heres the question, can I request for help so I can be better prepared next time over. Thank you in advance.
-- Findout Issues in this code, Bad practices in this Method
*********************************************************************************
Private Map<ID,String> updateAccounts(List<Account>(accList){
Map<Id, Account> updatedAccs = new Map<Id,Account>(accList);
Set<String> validAccTypes = new Set<String>{'Prospect', 'Customer'};
try{
Map<Id, String> errorMap = new Map<Id, String> ();
If(accList == null || accList.size() ==0)
Return errorMap;
For(Account acc:accList){
if(acc.DunsNumber.Lenght >9){
errorMap.put(acc.Id, 'Duns Number more than 9 Characters';
updatedAccs.remove(acc.Id);
}
} else If(acc.AccountNumber.Lenght >40){
errorMap.put(acc.Id, 'Account has more than 40 Characters');
updatedAccs.remove(acc.Id);
} else If(validAccTypes.contains(acc.Type)){
errorMap.put(acc.Id, 'Account Type is not Valid');
updatedAccs.remove(acc.Id);
}
Update updatedAccs;
} catch(Exception ex)
System.debug(ex.getMessage()0;
}
Return errorMap;
- Shanth Shenoy 3
- August 07, 2019
- Like
- 0
- Continue reading or reply
How to create a ListView with Inline Editing for Related Object?
- Greg Finzer
- February 26, 2019
- Like
- 0
- Continue reading or reply
How to Bulkify trigger handler Code
I want to update some task ownerid in my task trigger handler code. I have tried a piece of code which is not bulkified. Can you please help me with the bulkification of the same.
Thanks in Advance.
List<task> taskWithoutClosedCases = new List<Task>(); //Some logic to add tasks in the above List if(mapId_Case!= null){ for(task objTask : taskWithoutClosedCases){ if(isInsert){ if(objTask.Override_Default_Assigned_To__c == false && objTask.IsClosed == false){ List<Mapping__c> mappingRecord = [SELECT ID, Assigned_To__c FROM Mapping__c where Business_Unit__c=:objTask.Contact_Center_BU__c AND Task_Type__c=:objTask.Task_Type__c AND Type__c = 'Task Type - Assigned To']; if(mappingRecord.size() > 0){ if(mappingRecord.get(0).Assigned_To__c != null){ objTask.OwnerId = mappingRecord.get(0).Assigned_To__c; }else if(mappingRecord.get(0).Assigned_To__c == null && mappingRecord.get(0).Id != null){ objTask.OwnerId = UserInfo.getUserId(); } } } } } }
- Amlan Maiti
- February 21, 2019
- Like
- 0
- Continue reading or reply
String replacement regex System.NullPointerException: Attempt to de-reference a null object
Trying to return only the numbers from a phone number and remove extraneous data, works just fine, I removes brackets, lines, all clean code but when I run tests on my code I get back System.NullPointerException: Attempt to de-reference a null object.
String udp_billing_contact_number = serviceOrder[0].Billing_Contact_Phone_Number__c; String udp_contact_number = udp_billing_contact_number.replaceAll('[^0-9]', '');
- Jeremiah Sherrill
- February 21, 2019
- Like
- 0
- Continue reading or reply
File tagging in lightning
However, it appears that the TagCsv field is not available for files shared to an object record -- only files in a public library. It also appears that tagging is not supported in lightning.
Are there any recommended ways to implement something similar or some way to permit access to the TagCsv field on a contentversion uploaded to (shared with) a record?
My thoughts so far have been:
* Use the description field instead and add my tag at the beginning or end of it.
* Create a join object that implements tagging (RecordId, DocumentId, Tags (long text area)
* Embed a list of Ids in a custom field on the record of all the files selected for this purpose (yuck!)
- Bryan Leaman 6
- February 20, 2023
- Like
- 0
- Continue reading or reply
Identify specific batch job that created records
I would like to be able to create a trigger that could identify that the records are being created from a batch run (System.isBatch()) and then use the batch job Id to tie all those records together. So far I don't see any way to obtain this information in a trigger.
Ideally, I'd be able to do something like:
trigger on pkg__PackageObject__c (before insert) { if (System.isBatch()) { Id batchId = System.getBatchJobId(); for(pkg__PackageObject__c rcd : Trigger.new) { rcd.batch_job_id__c = batchid; } }But I can't find any such thing as "System.getBatchJobId()". I've found no way to instantiate Database.BatchableContext to peer into the current batch process being run.
- Bryan Leaman 6
- December 14, 2022
- Like
- 0
- Continue reading or reply
I need valid picklist value for record type in a test class
How can I ensure my test class will always use valid values for the picklist?
- Bryan Leaman 6
- December 02, 2022
- Like
- 0
- Continue reading or reply
CellAttributes in lightning-tree-grid
As an example, as I load the tree grid with data, booked sales will show in black, pending sales should show in yellow and the total should be red if it's below the sales target and green if it meets or exceeds the target.
I found reference to a column attribute called "cellAttributes" but I cannot find a definition of the "cellAttributes" object definition. The only examples in the documentation are to add icons to the cell. I've seen other examples of cellAttributes (on the datatable component) where a class can be added to the cells using cellAttributes:{class: {fieldName:'cellStyle'}}. But apparently this only works if you use slds- class names in your cellStyle field. It's better than nothing, but only a little.
Is there any way to have finer control over how cell contents are displayed in a lightning-tree-grid?
- Bryan Leaman 6
- October 14, 2022
- Like
- 0
- Continue reading or reply
lwc Need to refresh child component
Basically, I have something like:
<template> <c-child-lwc-component userid={selectedUserId}></c-child-lwc-component> <lightning-button label="Do Something" onclick={handleDoSomething}></lightning-button> </template>When the button is hit, I'm calling Apex to do something with the user id and when it's done, the childLwcComponent, if it re-renders properly, will show different results. But after calling the apex function, I cannot get the child component to re-render fully.
@track selectedUserId; import invokeMyApexMethod from '@salesforce/apex'MyClass.myApexMethod'; handleDoSomething() { invokeMyApexMethod({ userId: this.selectedUserId }) .then(result => { this.trackedfield = result; this.trackederror = undefined; // Need to re-load child component here! }).catch(error => { console.log(error); this.trackederror = error; this.trackedvalue = undefined; }); }I have tried using refreshApex referencing this.selectedUserId. I've also tried adding a dummy, tracked parameter to my child lwc component so that I can change that value every time my apex method has completed. but it still will not re-load the child component.
- Bryan Leaman 6
- September 22, 2022
- Like
- 0
- Continue reading or reply
How can I collect a debug log for an incoming API call?
I haven't coded SOAP apis into salesforce, but I see there are debug headers that are available. But I don't want debugging turned on for every call, just when I initiate a trace on the user.
Would adding debug headers to the API calls *always* generate logs? Or would it only generate logs when I define a user trace for the API user?
- Bryan Leaman 6
- June 15, 2022
- Like
- 0
- Continue reading or reply
How to tell which lightning or classic app is a user using
- Bryan Leaman 6
- May 25, 2022
- Like
- 0
- Continue reading or reply
Formula to show picklist text (not value!) on a related object
For example, if my picklist (Customer_class__c) had values defined as:
Value API Name
Enterprise Customer CC1
Business Customer CC2
Then from a related record, a formula TEXT(Account.Customer_class__c) will show "CC1" and I want to show "Enterprise Customer".
Any ideas? So far all I've come up with is to put a case statement in the formula:
CASE(TEXT(Account.Customer_class__c),
'CC1', 'Enterprise Customer',
'CC2', 'Business Customer',
... etc...
'Unrecognized code')
- Bryan Leaman 6
- April 07, 2022
- Like
- 0
- Continue reading or reply
Strange behavior of OAuth2 connected app definition
The strange behavior is that I can use the same Consumer_Key and Consumer_Secret with our production org host with a production username, password and API key and it ALSO works great. But I haven't moved the connected app definition to production yet!
How does this meet the definition of security? Am I missing something?
- Bryan Leaman 6
- April 06, 2022
- Like
- 0
- Continue reading or reply
Determine newly-pending approval step during approval
A challange with this approach is how to handle optional approval steps. For example, if a product sale requires customization, it enters a "Production" step and we want the document to reflect a status of "In Production". But if there's nothing to do it can move automatically to a "Delivery" step. However, I cannot find a way to determine during the triggerd field update that the Production approval step is being skipped due to conditional logic in the approval process.
I *have* found a way to see the currently pending approval step name, but during approval it still shows the step being approved, not the next applicable step. So after approval, if a step was skipped, any *new* update to the record would reveal it's at the Delivery step instead of "Production," but I cannot find a way to determine this at the time the prior step is being approved. So what we've had to do is duplicate the logic in code that we have in the approval process so our trigger can determine if the next step is being skipped or not. Very clunky!
Does anybody have a better way? It'd be great if we could just designate that skipped steps also update fields, or if approval processes could perform field updates upon entry to a step instead of just approval or rejection of a step.
Any thoughts?
- Bryan Leaman 6
- March 17, 2022
- Like
- 0
- Continue reading or reply
How can I check for Modify All Data permission in Apex?
But I'm unable to find a way to make this same kind of determination in Apex. My use-case is that I'd like to condition editability of some data based on the status of the record *AND* whether the user has been granted a custom permission *or* they are a system admin (so I don't have to keep adding all custom permissions to our system administrators). But I've been unable to find a way to check for "Modify All Data" authority on the running user.
- Bryan Leaman 6
- February 16, 2022
- Like
- 0
- Continue reading or reply
Lookup filters with lightning-record-form
Has anyone else had this issue and maybe reported it to Salesforce? We don't have development support, so they don't help me out with bugs that can only be discovered by writingcode. :(
- Bryan Leaman 6
- November 26, 2021
- Like
- 0
- Continue reading or reply
Trigger can no longer change user role in Winter 2022?
I've added debug statements and I see that the code is assigning a new role id to the user record in a before update trigger context on the user object, but that change is no longer being saved to the user record.
Can anyone else confirm this? I haven't found an open issue yet and salesforce support doesn't help us at all when custom code is involved.
- Bryan Leaman 6
- September 16, 2021
- Like
- 0
- Continue reading or reply
INSUFFICIENT_ACCESS to use Async SOQL
I found posts from 2017 & 2018 that Async SOQL was a pilot program that needed to be enabled in the org. We're halfway through 2021 -- is this still only a pilot program feature???
- Bryan Leaman 6
- June 09, 2021
- Like
- 0
- Continue reading or reply
Approval.unlock fails insufficient access to delete EntityLock
Op:Delete|Type:EntityLock|Rows:1
Delete failed. First exception on row 0 with id 04Z7e000000NUov; first error: INSUFFICIENT_ACCESS_OR_READONLY, insufficient access rights on object id: []
- Bryan Leaman 6
- April 12, 2021
- Like
- 0
- Continue reading or reply
sfdx Authorize an Org does not complete
I tried re-authorizing from my personal PC (running linux and month-or-so old versions of vscode and sfdx) and that failed as well.
I've just uninstalled and re-installed vscode and I still cannot authorize to any of my orgs.
- Bryan Leaman 6
- March 03, 2021
- Like
- 0
- Continue reading or reply
Build a layout component that can hold other lightning components
My use-case is a record page that really needs to be full-width. We use the tabs component to place related lists in one tab and other specialty functionality in other tabs. But now I'd like to add an activities side-bar to one of the tabs rather than to the page as a whole, but I can't find any "columns" components that would allow other components to be placed in them.
Am I missing seeing something obvious? I guess I could see if the accordion component is open-source and adapt that to various column configurations if I have to.
- Bryan Leaman 6
- August 07, 2020
- Like
- 0
- Continue reading or reply
Can fields on a related record component be editable
Did I take too long a leap of faith? It seems intuitive that if I need to provide an "Update record" action for the related record component to use, that I'd be able to update the record.
- Bryan Leaman 6
- August 04, 2020
- Like
- 0
- Continue reading or reply
Scheduled apex class did not run
This is NOT an issue of the job failing or aborting. Even if that happens, there's an entry in the list of Apex jobs showing that status. In my case, it seems that once or twice a week the Scheduled job list will show that the job was submitted, but it never shows up in batch and does not run.
Any thoughts? I tried calling salesforce support because it sounds like a platform issue in the scheduler, but we have to have developer support for them to look into why their job scheduler is failing. And developer support is too expensive. I've tried adjusting the start time, but so far that hasn't helped.
- Bryan Leaman 6
- June 16, 2020
- Like
- 0
- Continue reading or reply
Aura component combined requests only 1 gets a result
I've had to cascade my method calls so the second one is invoked when the first one completes. Then when the second one completes I can access its return data.
Note, I'm using aura because (as far as I can tell) lightningQuickAction isn't available in lwc yet.
(As a side note: I've noticed incomplete native components like today's tasks or list views on my home page don't always get filled in if the requests get combined as well.)
- Bryan Leaman 6
- March 13, 2020
- Like
- 0
- Continue reading or reply
Could not run tests on class <classid> because: connection was cancelled here
This has been a problem for over a year, but has been getting worse in the last few months.
- Bryan Leaman 6
- July 28, 2017
- Like
- 2
- Continue reading or reply
Synchronization check is not working Winter'16 (and earlier)
I upgraded my Force.com IDE to Winter'16 (v35) hoping it would resolve the issue, but it doesn't.
Please, there *has* to be a way to fix this! Even if I use the "Synchronize with server" to update my local copy, til I go through a dozen changes or so and then save the results to the server, someone else could've have already uploaded another change. If the IDE is going to go through a lengthy "Synchronize check against server" it should at least work properly.
At the moment, all I can figure to do is bring up a list of the classes/pages I'm about to upload and make sure I'm the last one to have updated them before I save to server.
- Bryan Leaman 6
- December 01, 2015
- Like
- 1
- Continue reading or reply
sfdx.cmd is not recognized as an internal or external command
'"C:\Users\Desja\AppData\Local\sfdx\client\bin\..\7.209.6-8ba3197\bin\sfdx.cmd"' is not recognized as an internal or external command, operable program or batch file.
>>> Why is it trying to run sfdx from that folder? It's not in that folder!
In this folder: C:\Users\Desja\AppData\Local\sfdx\client I have two sub-folders, "bin" and "7.209.6-8ba3197", the 2nd of which appears to have been created on 9/5/23 (just 2 days ago). The "bin" folder contains 2 files: sf.cmd and sfdx.cmd, while the "7.209.6-8ba3197" folder contains a "bin" folder, which contains a single file named "node.exe"
CLI has become a very valuable tool for me as I support 19 nearly identical orgs for the chapters of a national non-profit that works for the homeless. I have no idea why it has stopped working so mysteriously.
I have been through several existing messages on here that all seem to point to the PATH environment variable. The correct folder is present in my path, but the error message indicates it's trying to run sfdx from that other folder named 7.209.6-8ba3197\bin -- why?
Thank you for any clues to help resolve this.
- CRM_Pete
- September 08, 2023
- Like
- 1
- Continue reading or reply
Validation Rules, make fields not mandatory if value to other field iis Opportunity Lost?
OR(
$Profile.Name ="2F00eb0000000YhB7",
$Profile.Name ="2F00e9E000000ae9h",
$Profile.Name ="2F00eb0000000YhB1",
ISBLANK(NextStep),
ISBLANK( Next_Step_By__c ),)
but I'd like to add a condition: when the opportunity is Lost, these fields are no longer mandatory.
I tried to add this but it doesn’t work
AND(ISPICKVAL( StageName ,"Opportunity Lost"),NOT (ISBLANK( NextStep))),
Do you have any idea ?
- chris lim 15
- July 05, 2023
- Like
- 0
- Continue reading or reply
Try to insert data from api using batch
public with sharing class PokemonBatch implements Database.Batchable<SObject>,Database.AllowsCallouts{
public Iterable<SObject> start(Database.BatchableContext context){
return Database.getQueryLocator('SELECT Id FROM Pokemon__c');
}
public void execute(Database.BatchableContext context,List<SObject> scope){
List<Pokemon__c> pokemonList = new List<Pokemon__c>();
for (Object obj : scope) {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://pokeapi.co/api/v2/pokemon?limit=905');
request.setMethod('GET');
HttpResponse response = http.send(request);
// Check if Connection was successful
if (response.getStatusCode() == 200) {
//deserialize response
Map<String,Object> responseData = (Map<String,Object>) JSON.deserializeUntyped(response.getBody());
List<Object> results = (List<Object>) responseData.get('results');
//get url of pokemon's endpoints
for (Object result : results) {
Map<String,Object> pokemonData = (Map<String,Object>) result;
String pokemonUrl = (String) pokemonData.get('url');
//Make call to new endpoint
HttpRequest detailsRequest = new HttpRequest();
detailsRequest.setEndpoint(pokemonUrl);
detailsRequest.setMethod('GET');
HttpResponse detailsResponse = new Http().send(detailsRequest);
// Check if Connection to the new endpoint was successful
if (detailsResponse.getStatusCode() == 200) {
//deserialize response
Map<String,Object> detailData = (Map<String,Object>) JSON.deserializeUntyped(detailsResponse.getBody());
// get fields from detail data
//***** get the id
Integer id = (Integer) detailData.get('id');
//***** Check if the id is greater than the number of pokemons we want to get
//***** we only want the pokemons until the 8th generation
if(id > 905){
return;
}
//***** get and convert height and weight to the correct units
Double height = (Double) detailData.get('height')/10;
Double weight = (Double) detailData.get('weight')/10;
//***** get the name
String name = (String) detailData.get('name');
//***** get and handle multiple types
List<Object> types = (List<Object>) detailData.get('types');
List<String> typeList = new List<String>();
for (Object type : types) {
Map<String,Object> typeData = (Map<String,Object>) type;
Map<String,Object> typeName = (Map<String,Object>) typeData.get('type');
String nameType = (String) typeName.get('name');
typeList.add(nameType);
}
//***** get species url to adquire the generation
Map<String,Object> species = (Map<String,Object>) detailData.get('species');
String speciesUrl = (String) species.get('url');
// make a call to the species endpoint
HttpRequest speciesRequest = new HttpRequest();
speciesRequest.setEndpoint(speciesUrl);
speciesRequest.setMethod('GET');
HttpResponse speciesResponse = new Http().send(speciesRequest);
// Check if Connection to the new endpoint was successful
if (speciesResponse.getStatusCode() == 200){
//deserialize response
Map<String,Object> speciesDetails = (Map<String,Object>) JSON.deserializeUntyped(speciesResponse.getBody());
//***** get the generation url and extract the the generation number from the end
Map<String,Object> generationDetails = (Map<String,Object>) speciesDetails.get('generation');
String generationUrl = (String) generationDetails.get('url');
String generation = generationUrl.substring(generationUrl.length() - 2, generationUrl.length() -1);
//***** get the sprites
Map<String,Object> sprites = (Map<String,Object>) detailData.get('sprites');
String spriteUrl = (String) sprites.get('front_default');
//***** create a new pokemon object and insert the data extratted fom the API
Pokemon__c pokemon = new Pokemon__c(Name=name.capitalize(),
PokeIndex__c=id,
Peso__c = String.valueOf(weight + ' kg'),
Altura__c = String.valueOf(height + ' mts'),
Tipo__c = String.join(typeList, ';'),
Geracao__c = Integer.valueOf(generation),
Foto_URL__c = spriteUrl
);
pokemonList.add(pokemon);
}
}
//***** insert list of records only if the list is not empty
}
}
}
if (!pokemonList.isEmpty()) {
insert pokemonList;
}
}
public void finish(Database.BatchableContext context){
// nothing
}
}
but the batch do not insert anything it shows completed but 0 batches processed. Any thoughts?
- Paulo Proença
- July 03, 2023
- Like
- 0
- Continue reading or reply
AvoidDeeplyNestedIfStmts: Deeply nested if..else statements are hard to read
Need to resolve the warning, which is 'AvoidDeeplyNestedIfStmts'."
Using the following code, I am getting a warning about
Deeply nested if..else statements are hard to read (rule: Design-AvoidDeeplyNestedIfStmts)apex pmdAvoidDeeplyNestedIfStmts
Example code:
if(String.isNotBlank(brand)){
if(brand.contains(';')){
arrTemp = brand.split(';');
filterTemp = '';
for(integer i=0; i< arrTemp.size(); i++){
String valueTemp = arrTemp[i];
if(String.isNotBlank(valueTemp)){
filterTemp += ' XC_Brand__c = \'' + valueTemp + '\' OR';
}
}
if(String.isNotBlank(filterTemp)){
filterTemp = filterTemp.removeEnd(' OR');
prodFilterString += ',(' + filterTemp + '),';
}
}else{
prodFilterString += ',XC_Brand__c = \'' + brand + '\',';
}
}
"I have highlighted the issue."
Please help me out.
Thanks!
- Mounika@9999
- July 03, 2023
- Like
- 0
- Continue reading or reply
How to insert the duplicate record is any way to insert the duplicate record using Apex
Error Response : [{"errorCode":"APEX_ERROR","message":"System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATES_DETECTED, You're creating a duplicate Lead record. We recommend you use an existing record instead.: []\n\nClass.LeadReceiver.doPost: line 13, column 1"}]
- Dheeraj shokeen
- June 28, 2023
- Like
- 0
- Continue reading or reply
SOQL query returns no results Trigger but returns a row in Developer Console for ContentDocumentLink Object.
trigger emailToPostChatter on EmailMessage (After insert) {
List<FeedItem> itemList = new List<FeedItem>();
List<FeedItem> upItemList = new List<FeedItem>();
List<ContentVersion> conVersionList = new List<ContentVersion>();
List<FeedAttachment> atchList = new List<FeedAttachment>();
List<FeedAttachment> FeedAtchList = new List<FeedAttachment>();
List<ContentDocumentLink> contDocLinks = new List<ContentDocumentLink>();
Set<Id> EmailId = new Set<Id>();
for (EmailMessage email : trigger.new) {
FeedItem post = new FeedItem();
post.ParentId = email.ParentId;
post.Visibility = 'AllUsers';
post.Body = email.FromName + '\n' + email.TextBody;
system.debug('Body = '+post.Body);
insert post;
system.debug('EmailMessage Id= '+ email.Id);
system.debug('message.ContentDocumentIds = '+email.ContentDocumentIds);
system.debug('Post ID 1= '+ post.Id);
system.debug('message.HasAttachment = '+email.HasAttachment);
if(email.HasAttachment){
system.debug('EmailMessage Id inside If = '+ email.Id);
//emailToPostChatterHelper.InsertFeedAttachment(email.Id, Post.Id);
List<ContentDocumentLink> contDocLinks = [select Id, LinkedEntityId, ContentDocumentId from ContentDocumentLink where LinkedEntityId =: email.Id];
//List<ContentDocumentLink> contDocLinks2 = [SELECT Id, ContentDocumentId, ContentDocument.LatestPublishedVersion.VersionData FROM ContentDocumentLink WHERE LinkedEntityId = :email.Id];
system.debug('contDocLinks = '+contDocLinks);
//system.debug('contDocLinks2 = '+contDocLinks2);
system.debug('LinkedEntityId = '+email.Id);
system.debug('contDocLinks Size = '+contDocLinks.size());
if(contDocLinks.size()!=null){
for(ContentDocumentLink contD : contDocLinks){
ContentVersion contv = [select Id from ContentVersion where ContentDocumentId =:contD.ContentDocumentId];
system.debug('contv ='+contv);
FeedAttachment feedAttachment = new FeedAttachment();
feedAttachment.FeedEntityId = post.Id; //Id of FeedItem
feedAttachment.RecordId = contv.Id;
system.debug('feedAttachment.RecordId ='+feedAttachment.RecordId);
//feedAttachment.Title = 'FileName';
feedAttachment.Type = 'CONTENT';
insert feedAttachment;
}
}
}
}
}
- Satish Kumar Lalam
- June 27, 2023
- Like
- 0
- Continue reading or reply
- Vishal Saw
- June 22, 2023
- Like
- 0
- Continue reading or reply
count value should get incremented across each batch
integer count should always maintain its value eg: if count is 2 in first batch than in second batch it should start with 3
please give a solution on this
global class BatchAccountAssetRoleConsolidation implements Database.Batchable<sObject>, Database.Stateful { private Map<String, Integer> accountAssetRoleCountMap = new Map<String, Integer>(); private Integer successCount = 0; private Integer errorCount = 0; Integer count = 0; global Database.QueryLocator start(Database.BatchableContext BC) { String query = 'Select id, Account__c, Contact__r.AccountId, Asset__c, Role__c, Account_Asset_Role__c from Account_Asset_Relationship__c'; return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<Account_Asset_Relationship__c> aarLst) { Set<String> uniqueValues = new Set<String>(); for(Account_Asset_Relationship__c aar : aarLst) { String key; if (aar.Account__c != null && aar.Role__c != null) { key = ((String) aar.Account__c + (String) aar.Asset__c + aar.Role__c); } else if (aar.Account__c == null && aar.Role__c != null && aar.Contact__c != null) { key = ((String) aar.Contact__r.AccountId + (String) aar.Asset__c + aar.Role__c); aar.Account__c = aar.Contact__r.AccountId; } else if (aar.Account__c == null && aar.Role__c == null && aar.Contact__c != null) { key = ((String) aar.Contact__r.AccountId + (String) aar.Asset__c); aar.Account__c = aar.Contact__r.AccountId; } else if (aar.Account__c != null && aar.Role__c != null && aar.Contact__c != null) { key = ((String) aar.Account__c + (String) aar.Asset__c + aar.Role__c); } else if (aar.Account__c != null && aar.Contact__c != null && aar.Role__c == null) { key = ((String) aar.Contact__r.AccountId + (String) aar.Asset__c); } else { continue; } if (accountAssetRoleCountMap.containsKey(key)) { count = accountAssetRoleCountMap.get(key); while(uniqueValues.contains('duplicate ' + count)){ count++; } aar.Account_Asset_Role__c = 'duplicate ' + count; accountAssetRoleCountMap.put(key, count + 1); uniqueValues.add('duplicate ' + count); } else { accountAssetRoleCountMap.put(key, 1); aar.Account_Asset_Role__c = key; } } try { List<Database.SaveResult> saveResults = Database.update(aarLst, false); for(Database.SaveResult sr : saveResults) { if (sr.isSuccess()) { successCount++; } else { errorCount++; } } } catch(Exception e) { System.debug(e); errorCount += aarLst.size(); } } global void finish(Database.BatchableContext BC) { // execute any post-processing operations like sending email System.debug('Batch finished with ' + successCount + ' successful records and ' + errorCount + ' error'); } }
- himanshu huske 7
- April 07, 2023
- Like
- 1
- Continue reading or reply
- Kishor Kumar 120
- March 31, 2023
- Like
- 0
- Continue reading or reply
trigger to populate the account field with opportunity having max amount
I have a field in Account as Top_Opportunity__c which is a lookup to opportunity. I need to write a trigger to populate the same field with the child opportunity having maximum Amount (In all after triggers).
Can someone please help me with this. Thanks in advance:)
- Sreelakshmi Asokan
- March 31, 2023
- Like
- 0
- Continue reading or reply
File tagging in lightning
However, it appears that the TagCsv field is not available for files shared to an object record -- only files in a public library. It also appears that tagging is not supported in lightning.
Are there any recommended ways to implement something similar or some way to permit access to the TagCsv field on a contentversion uploaded to (shared with) a record?
My thoughts so far have been:
* Use the description field instead and add my tag at the beginning or end of it.
* Create a join object that implements tagging (RecordId, DocumentId, Tags (long text area)
* Embed a list of Ids in a custom field on the record of all the files selected for this purpose (yuck!)
- Bryan Leaman 6
- February 20, 2023
- Like
- 0
- Continue reading or reply
One user can't create ContentVersion
We have a script that does a HTTP callout to create a PDF, the callback saves this PDF in Salesforce as a document.
We have this working for multiple objects and this works fine. But for one type, one user, has an error that we can't seem to resolve.
The user is a System admin, other system admins can run it without issues, even profiles with less rights (sales user) can run it without issue.
But whenever this user runs it, he gets this error that we don't understand:
System.DmlException: Insert failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, common.exception.SqlNoDataFoundException: ERROR: query returned no rows Where: PL/sdb function doc.contentfolders.get_root_fdr_details(character varying) line 16 (SFSQL 286) at SQL statement SQLException while executing plsql statement: {?=call ContentFolders.get_root_fdr_details(?)}(07H09000000D1Dj) SQLState: P0002 Where: PL/sdb function doc.contentfolders.get_root_fdr_details(character varying) line 16 (SFSQL 286) at SQL statement File: plsdb_exec.c, Routine: exec_stmt_execsql_body, Line: 3307 [conn=STANDARD:1:1:108918:1]: [] Class.HttpCallout.processContract: line 77, column 1the code it fails on is this:
Callout calloutObj = (Callout)JSON.deserialize(calloutString, Callout.class); HttpRequest req = setupHttpRequest(calloutObj); HttpResponse res = makeRequest(req); Quote q = [SELECT Name FROM Quote WHERE Id= :recordId LIMIT 1]; ContentVersion conver = new ContentVersion(); conver.ContentLocation = 'S'; conver.PathOnClient = 'Contract.pdf'; conver.Title = 'Contract_' + q.Name; conver.VersionData = res.getBodyAsBlob(); conver.Type__c = 'Contract'; insert conver; <=== Line 77
As I said, works fine for everyone, but this one specific user we get this error.
Anyone an idea how to fix this? We don't even understand the error completely...
- Nick Verschueren
- February 20, 2023
- Like
- 0
- Continue reading or reply
Automatically get Previous dates value to present day.
I want Previous days value to automatically subtract with present days value.
Example: It's a car related app, where I need to track daily Kilometres odometre reading.
"Opening day reading - closing day" reading is to be monitored daily.
Where todays closing reading should be tomorrow opening reading automatically..
So once user is on Board, you just need to enter opening reading once and daily user must only enter closing reading.
So only once closing readng is entered, automatically the formula should detect previous days closing reading.
Sorry for the long and complicated explanation for the question, just trying to explain how the forumale should work, accordingly you all can suggest...
Thanks
- Syed Asfaan
- February 20, 2023
- Like
- 0
- Continue reading or reply
How to create custom/different formula to each user. Approx 200 different forumlae for 200 people.
I have over 200 Community user using my app, How do I create custom forumula for each user?
Also, Can I create 200 page layouts for 200 users?
Custom forumula in the sense , its a small accounts app where each user has different banks for cash and POS transactions for their requirements.
Mostly fields would be common but forumalas for each user would be different.
I want only particular fields for that user to display with those particular formulae.
Thanks
- Syed Asfaan
- February 20, 2023
- Like
- 0
- Continue reading or reply
API Rest Contact integration problem: duplicated record error
Hi, We have a custom rest service in Salesforce invoked by another external system to upsert contacts. This service is invoked by POST method, and then it makes an upsert operation of the record received, which is identified in the json by a custom field checked as External ID. The service is invoked from different events sending different data of the same record, and each event is a different request to the service. Those events are sent at the same time and we cannot control the order. For example, we have 4 requests of the same record, one at 15:15:30.539, other at 15:15:31.385, other at 15:15:31.443 and the last one at 15:15:31.444. The point is, the first request returns an OK and the Salesforce Id of the contact created, but then the rest of requests return the next error: "errorMessage":"duplicate value found: User_External_Id__c duplicates value on record with id: 0037Z00001gvEdZ". We have tried all different requests of each event separately via Postman, and everything works perfect, it first creates the record and then just update, as expected. I can't understand why it isn't working when the requests are at the same time, when the dml operation is always an upsert, so it should never detect a duplicate. What do you think could be the problem? Thank you in advance. Regards |
- Eva Diaz 9
- December 29, 2022
- Like
- 0
- Continue reading or reply
Apex Triggers vs Record Triggered Flows - Considerations & Best Practice
Since I am aware of the general best practice to make sure that out-of-box automation tools are being utilized properly I am wondering what are the cons and pros of two approaches I have in mind:
1. Have all automations STARTING with Flows, being extended by Apex Code only as and when it's needed.
2. Writing Apex Triggers to handle automations.
How does that translate to efficiency?
I think that the approach with Flows being defined for all objects as initiators of automations can help easily visualize the automation path. Say I would like to write a custom Apex Class that sends the data to another system via HTTP to push the same data to the other platform whenever a record is created.
Do you think that defining a Flow Trigger that then calls an Apex Class is a good practice?
Also, perhaps there are considerations about whether we need to re-process some data in SF when we receive a response, then perhaps Before-Save operation would be more efficient and for that reason alone we might want to go with Apex Trigger (since you can call Apex only in After-Save flow?) - so that's perhaps another consideration.
Let me know your thoughts folks - I think more or less I am right about the above, but I want to make sure that I am not missing any additional factors to ponder upon.
Thanks,
Seb
- Sebastian Kalota
- December 06, 2022
- Like
- 0
- Continue reading or reply
I need valid picklist value for record type in a test class
How can I ensure my test class will always use valid values for the picklist?
- Bryan Leaman 6
- December 02, 2022
- Like
- 0
- Continue reading or reply
REST API not triggering Record-Triggered Flows on Method Call
I looked at the docs and saw that there is the ability to trigger a flow from the REST API, but I assumed this would be taken care of automatically since the flow itself is triggered from a record change. The issue is that the flow itself is just never being run, including the check, which dictates how data is changed. Is there something I am missing here? They say that the same workflow can be kicked off from the Dataloader when creating new records. Am I missing a toggle with the REST API?
- Logan Pelletier
- November 15, 2022
- Like
- 0
- Continue reading or reply