• Bryan Leaman 6
  • NEWBIE
  • 440 Points
  • Member since 2015

  • Chatter
    Feed
  • 11
    Best Answers
  • 3
    Likes Received
  • 0
    Likes Given
  • 40
    Questions
  • 111
    Replies
When I try to run sfdx the same way I have for about 4 years, I get this error message:

'"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.
I created this Validation Rule that when a user with a specific profile creates or modify an opportunity, he must fill in the Next step fields  
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 ?

 
I´m trying to get data from PokeAPI and insert in a Customo object and this is what i have so far.


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?
Hi All,
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!
Status Code :    500
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"}]
I have wrote a trigger on EmailMessage Object to get the attachments from email replies to case FeedItems. Below is my code Snippet. I am facing an issue with SOQL query on ContnentDocumentLink object. Where the the same query is working fine in Anonymous window but not in trigger. Could you please advise on this. Below is my Code Snippet. Kindly advice on this.

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;
}
}

}
}
}
Account_Asset_Role__c field is unique, we have integer count, while bulk updation if duplicate value is found on Account_Asset_Role__c field, feild will be updated as (duplicate + count) duplicate 1, duplicate 2..... when the new batch starts count again comes to 1
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');
                     }
                     }

 
Hi,

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:)
I have a need to provide a way for people to select which uploaded/related files fulfill a specific purpose (essentially, which file s provide proof of authorization).  I was hoping to use the TagCsv field and when they select the file, update the tags to indicate which file(s) provide that authorization.

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!)

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 1
the 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...
Hello

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 
Hello All,
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
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
Hello all,

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
We have a picklist used by marketing to designate special pricing programs. This object in question also has several record types. Ideally, the same values would always be defined as available for all record types, but when they aren't my test class can't tell which ones are valid for the record I'm creating for the test. Also, I can't call out in a test to the metadata api to obtain valid values by record type. This picklist is a global picklist, so it must be restricted to the defined values.

How can I ensure my test class will always use valid values for the picklist?
Have a user utilizing one of our API products to insert new records and update existing ones. A workflow has been created on the user account that should auto-fire when any record is inserted or updated. However, said flow is never fired.

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?