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

  • Chatter
    Feed
  • 11
    Best Answers
  • 3
    Likes Received
  • 0
    Likes Given
  • 40
    Questions
  • 111
    Replies
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 ?

 

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

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.

Lead Time Zone FieldTask Time Zone
Hi, 
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
Hi Guys,
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"
User-added imageUser-added image
Here's my email handler
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;


 
  • February 16, 2022
  • Like
  • 0
I need to send Asynchronous requests to some 3rd party API and that call method should be @future. 
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?
 
Hi Friends from the Salesforce Forum,
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;

 
I have a custom object called Renovation and a child object called Renovation Element. I want to create a ListView on the Renovation Lightning Page with inline editing enabled that has a list of the Renovation Elements. The Renovation Element custom object is not available to be chosen in the Object Drop Down List when creating the list view. Why is that? How do I create a New List View of Renovation Elements that are related to the Renovation? FYI, I have Inline Editing enabled and also enhanced lists enabled in the org.
Hi All,
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();
					}
				}
			}
		}
	}
}

 

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]', '');

 
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 use a managed package that uses a batch job to create records. But they don't provide any field to group those records together to see what any specific batch job created them. 

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.
 
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?
I have a project to display sales grouped by division, region, store and salesperson that appears to lend itself to a tree grid display component. However, I will need to adjust cell styles based on the content of a cell and I have not found a way to do that yet.

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?
 
I've been unable to force a refresh of a child component in lwc.
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.
 
We have a third-party integration with our salesforce org. I believe they're using SOAP api calls at API version 41.0.  The calls are creating data in our org and those record inserts and updates fire custom triggers. However, when I add a user trace for the API user, I don't get any logs of the activity. 

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?
Is there any way to report or check which app a user is using or to track usage of apps?
I leveraged the new-ish feature of picklists that lets me have a value that is displayed and a code that is stored in the object record and they're different.   However, now I'd like to show the picklist value (not the code) on a related object, but the only thing I can find is to do TEXT(object__r.picklistfield__c), which always returns the code, not the value.

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')
I've developed some code using Salesforce REST APIs to perform simple queries from external systems. I've created a Connected App definition in my sandbox and connect to it using https://{sandbox-host-name}.my.salesforce.com with grant_type=password, our client_id, client_secret, username & password+api key and it works great.

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?
We have some approval processes that control the flow of a document through a series of stages. To accomplish this we have field updates upon approval & rejection to set the new stage.

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?
I love how we can filter lightning components on standard permissions rather than looking for specific profile name or creating custom permissions. For example, instead of someting like  Profile > Name = 'System Administrator' I can show a component based on "Permissions > Standard Permissions > Modify All Data = true".

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.
I tried implementing a new lookup field with a filter on a picklist field in the same object. When using the native record layout screen it works properly -- if I change the picklist, I get a different set of records in the lookup search screen. But when I try presenting the fields in a lwc using lightning-record-form the lookup filter is stuck on the already-saved picklist value rather than whatever I've changed it to.

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. :( 
We have a trigger that changes a user's role based on changes made to the User.Division field, but as of Winter 2022 it is no longer working.  

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.
When I try to use Async SOQL I'm getting an error that I have insufficient access to query this object ... with Async SOQL.  The Id provided in the error starts with "01I" and I cannot determine what this is. I'm a full system admin.  

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???
I'm trying to use the Approval.unlock and Approval.lock methods to allow specific updates to locked records, but I'm getting an error indicating my user is not authorized to delete records from EntityLock. How do I give someone access to delete EntityLock records? I don't see it in object authorities.

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: []
 
Starting yesterday my authorization token became invalid, but when I tried to re-authorize my org the process just hangs at "waiting for localhost" in the browser. I'm using Windows 10 and the latest vscode and the latest sfdx and both were last updated several days ago and had been running fine.

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.
I'd love to be able to create a component like Accordion that is basically a layout component to create columns like the general page layout does.

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.
I'm adding a tab to an object's lightning page where I want to provide a way to edit fields on a related record. I am able to select the update action for my related record and set the layout with the fields I want, but they are not 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.
I've scheduled a handful of Apex classes to run daily functions after normal business hours. They have been running just fine for over a year. But recently (last month or so), sometimes the first job in the sequence doesn't run.  It shows that it was submitted on the scheduled job list, but never appears in the list of Apex jobs that started and ran.

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.

Scheduler says it started

Did not start
 
I've noticed issues with the lightning framework when multiple requests are combined. I'm working on a new quickAction lightning aura component and I'm issuing 2 calls to my controller for 2 different pieces of information. When the lightning framework combines the requests into a single call to the server I can see both responses in the return payload (using Chrome developer tools), but only 1 of my method calls' callback functions gets invoked. The other does not, so I cannot access the returned data.

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.)
I'm constantly unable to complete tests because of this error in our sandboxes. If I keep running them over and over they usually complete normally eventually, but it can waste a half hour of my time to get them to complete so I have an accurate test coverage percentage on the class in question.

This has been a problem for over a year, but has been getting worse in the last few months.
When I first started developing a year ago (and I forget which version I was using at the time), I seem to recall that I'd get a warning if the server code was newer than the copy I was working with. This is no longer happening.  We have multiple developers working in our sandbox and recently discovered that when I save my apex code, VF pages, etc., the Force.com IDE is simply saving overtop of whatever is on the server without any warning that the server code changed since I last refreshed my local copy.

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. 
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?