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

  • Chatter
    Feed
  • 9
    Best Answers
  • 3
    Likes Received
  • 0
    Likes Given
  • 39
    Questions
  • 95
    Replies
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]', '');

 
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.)
For better control over the frame size, I've implmeneted a lightning component that displays a visual force screen in an iframe rather than using the build-in visualforce lightning component. 

It was working fine, but now that we've enabled communities, I'm getting a full set of classic page headers in my iframe that I never used to have. Also, links to record pages are not working properly.  How can I pull in the visualforce page and NOT include headings?
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. 
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
I am looking for the best design to make a daily scheduled callout to process 10s of thousands of records. My plan is to create a schedulable apex class that runs a batch apex. In the start of the batch apex I make the callout and I get back the records from the API. In the execute method, I go through the records and upsert the records into Salesforce. Is this a sound approach? My only concern is that the call out to the api and the processing of the batch (start and execute methods) run in the same context so if the callout takes 3-4 seconds there is the risk of this becoming a long running transaction. My question is first am i correct in having this concern and if yes, how can I make the callout its own async transaction and then once the callout response is recieved then to process the records through batch apex.
I'm working with Opportunity object and OpportunityDetails object that have a master-detail relationship with one another. The master's api name is Opportunity and the detail's api name is Opportunity__Details__c.I have created a custom field in the Master object OppStatus__c.In that field I want to display the minimum status  of field Status__c value of Detail object. The field Status__c is a picklist value field with values Closed,Pending,New . And i have multiple records in the detail object .
(If the Status field in any record contains New, then it should update OppStatus field with New. 
I meant if in the records, 
for eg, Record 1 the field Status has value Closed
            Record 2 value is New, Record 3 value is Pending
           Record 4 value is Closed 

Then value should be updated in oppstatus is New. 
If in Record 2 , the value is pending or closed insted of new., the min value is pending. 

If all the values are closed, then the value closed should be updated. 

Like new is the minimum if new is not present, pending is the min. 
if pending is not present, closed is the min.) 
How to populate the field in master object. 
Thanks. 
  • January 03, 2023
  • Like
  • 0
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,

If the Asset status field equals "Inactive" and the "Inactive Reason" field equals "Missing/Lost Items", "Stolen Units" and "Trade-in" and a user tries to reactivate an Asset  by changing the status field from "Inactive" to "Instaled,", the system must display a sort of "Alert Box" with 'Yes' and 'No' Button, with the message "Do you want to create a support ticket to request the approval for the Asset reactivation"
1).If the user clicks on "Yes", the system must create a support ticket and send an approval message to the manager in charge whenever an inactive Stolen Unit is reactivated.
2).If the user clicks on "No", there is no action, leaving the asset record with no changes.

Thanks!!
  • December 23, 2022
  • Like
  • 0
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.
 
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
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?
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?
 
trigger addCase on Account (After update) {
   List<Account> allAccounts = new List<Account>([Select id,Fuzion_Status__c,(select id from cases where status in('New','Open')) from account where id in :Trigger.new]);
   List<Case> newCases = new List<Case>();
    
    for(Account myAccount :allAccounts){
    Account oldAccount = trigger.oldMap.get(myAccount.id);
    if(oldAccount.Fuzion_Status__c == 'Initial Phone call' && myAccount.Fuzion_Status__c != 'Initial Phone call'){
        if(myAccount.cases !=null){
            Case c = new Case();
            c.Accountid = myAccount.Id;
            c.Type = 'ICM';
            c.Origin = 'WEB';
            c.Division__c = 'Case Management';
            c.Status = 'New';
            c.RecordTypeId = '01236000000OJLq';
            newCases.add(c); 
        }
     }
        
    }
    if(!NewCases.isEmpty()){
        insert newCases;
    }
 
}
This is my code to create a case and I have just create an object called fuzion status but why it still shows variable does not exist?User-added imageUser-added image
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?
Hi Everyone, I have a requirement where we need to make more than 100 API calls in real time. As we all know that will hit governor limits.
We can't use Batch to call the API's . What is the best way to handle such situation ?