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

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

 
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?
We're getting ready to turn on the ability of our users to send salesforce email (email from an account, etc) via Outlook 365. But what we *really* want to do is to FORCE them to do it this way. We want to ensure Outlook 365 has a record of the outbound emails. 

However, I see no way to set this preference for everyone other than to log in as each user and choose the setting for them. With over 1000 users, that's a bit ridiculous.

Does anyone know a better way to enforce and administer this?
--Bryan
I have a simple SOQL query that I can run using developer console or workbench and it runs fine. But when I copy/paste it into anonymous apex it complains the the field I'm requesting does not exist.  How can that be?  I am running this as a system admin and I *do* have authority to the field. 

Here's a screenshot showing the query in developer workbench side-by-side with anonymous apex and the results.

SOQL Query vs Apex soql query
 
I've had a user today who has received an "Insufficient Priviledges" error when trying to export report details. He has authority to export reports. He created the report and can export the printable view. When I log in as this user I can pull up the report and export details with no problem. After rebooting his computer he was able to export the report again, but later got the same error on a different report. Again, *I* can export it when I log in as him, so it seems a very persistent glitch.  There has not been any change today to the user record or the profile assigned to him.
 I have a user who regularly gets a salesforce internal error when navigating to recor detail pages in lightning:
Looks like there's a problem.
An internal server error has occurred Error ID: 275320530-4767 (-683249219)

He's clicking a link on a list of records and the link simply goes to the native record detail page for the record. Usually just refreshing the page will eliminate the error and the record will be displayed. 

I've seen the same error and attempted to grab debug logs, but they always look fine. The only difference I see is that when I get this error it appears that maybe two requests are being bundled, but they both succeed (no errors in the logs at all -- just a simple soql query that returns results). Again, refreshing the page often works, and then I see the requests coming through on separate logs.
I need to access sforce.one in javascript inside a visualforce page that I'm including in a lightning component via iframe.

If I use the native "VisualForce" component then sforce.one is defined for me. But I'm short on vertical space and don't want to waste any on an extraneous title line and also I need to control the iframe height dynamically. So I created a simple component that includes the VF page in my own iframe, but sforce.one is NOT defined when I do it that way.

 
We have a trigger to provide certain validations that were difficult as validation rules (and need to be enforced even when created by pushing through an approval process). 

We're also in the process of moving to lightning. So I've placed our VF page in a lightning component, but when the "Submit for Approval" button on the approval related list is used and the result violates the rule in the trigger, we just get a gray screen that looks like a Chrome connection error with the message: 
     "... salesforce.com refused to connect" 

I found that if I postpone the error until the next step in the approval process, then trying to submit the record works and the error is correctly displayed when trying to approve the next step. I suspect this is an issue of using the "Submit for approval" button on a VisualForce page embedded in a lightning VF component.

The custom error message is also handled correctly when using the native lightning submit button.
I have a component using force:recordData components to perform updates on a selected record from a list. Everything *had* been working fine, but now I'm getting an error message I cannot explain or trace to the cause.

The scenario is that when a button is clicked, I update the recordId on my force:recordData component and call reloadRecord(). My recordUpdated handler gets called for a "LOADED" event, does nothing but log that it was called and exits.

Then I display a modal form with a handful of fields from that record. They show up with the correct values from the reloadRecord() call.

When a button is clicked I issue a saveRecord() call. My recordUpdated handler gets called for a "CHANGE" event. I hide the modal, fire a toast event and exit.

After my recordUpdated handler has completed I get a "Sorry to Interrupt" error message: "Error in $A.getCallback() [Neither a quick action or a quick action record collection. "

The root callstack entry for the exception is "dev.lightning.force.com/libraries/force/recordLibrary/crud.js:19:446"

I have console.log statements at every entry and exit point and it looks like no more of my code is running after exiting the recordUpdated handler (and nothing else *should* be running after that).

I'm at a loss how to proceed.
I have a lightning component using force:hasRecordId.  What I've been trying to do (unsuccessfully) is have a subform that just needs one lookup field and automatically fill in the current parent object's record Id and write the new related record.

The problem is the fields don't even render. Hidden in the html is
<span class="slds-hide">
 "No input rendered: "
"Field "undefined" not found in response."
</span>

I've used lightning:recordeditform before, but only to create & update the object record who's page I'm on, not a related list record.

I'm getting the main record's data using force:recordData (this works fine):
<force:recordData aura:id="dealEditor"
        recordId="{!v.recordId}"
        fields="Id,Name"
        targetFields="{!v.dealFields}"
        targetError="{!v.dealError}"
        recordUpdated="{!c.dealHandleRecordUpdated}"
        mode="EDIT"
    />

On successful load of the force:recordData  I'm setting the new credit application's Proposal__c field so the new record will be properly linked: 
component.find("newca_proposal").set("v.value", component.get("v.dealFields.Id"));

And I want to allow lookup of one field and then write a related record:
<aura:attribute name="newCreditAppId" type="String"/>
                <lightning:recordEditForm aura:id="newcreditapp"
                    recordId="{!v.newCreditAppId}"
                    objectApiName="dealer__Credit_Application__c"
                    onsubmit="{!c.newCreditAppSave}"
                    class="slds-card__body_inner"
                >
                    <lightning:inputField fieldname="Finance_Company__c" aura:id="newca_financecompany"/>
                    <lightning:inputField fieldname="Proposal__c" aura:id="newca_proposal"/>
                    <lightning:button type="submit" label="Add Finance Company"/>
                </lightning:recordEditForm>

Is this possible? What am I missing?
Our lightning home pages regularly present a server error to our users. We get a "Sorry to interrupt" window that says: This page has an error. You might just need to refresh it." But refreshing doesn't always work. If I click on any other tab in my lightning app and come back to the Home screen it always works fine.
I opened a support case and they refuse to help other than to say there's an error in my visualforce page. But if that were the case I would expect it to NOT work most of the time and NOT work when I switch to another tab and come back to home, where the data to be displayed will not have changed one iota.

Error message details:
This page has an error. You might just need to refresh it. First, would you give us some details? (We're reporting this as error ID: 1063741991)

Technical Stuff:
[NoErrorObjectAvailable] Unable to retrieve Visualforce page url.
eval()@https://mbw.lightning.force.com/components/flexipage/visualforcePage.js:3:390

I tried to report this to salesforce as an error because it looks like the lightning visualforcePage component is generating an error that is beyond my control as a developer.
I was trying out a simple example utility bar component. The sample just has a button that uses the Utility API to change the utility bar component's label.

What I wanted to do was to change the button label when the component is first initialized, eventually based on data I would read from a configuration. So I declared a handler for the "init" event and attempted to set the label to a fixed value there:

<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
    <lightning:utilityBarAPI aura:id="UtilityBarEx" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <lightning:button label="set Utility Label" onclick="{! c.setUtilityLabel }" />
</aura:component>

and my controller's doInit method 
({
    doInit : function(component, event, helper) {
        var utilityAPI = component.find("UtilityBarEx");
        utilityAPI.setUtilityLabel({label: 'Salesforce Utility Label'});
    },
    setUtilityLabel: function(component, event, helper) {
        var utilityAPI = component.find("UtilityBarEx");
        utilityAPI.setUtilityLabel({label: 'Salesforce Utility Label'});
    },
})

This results in the erorr:
aura_prod.js:890 null "Error: Invalid or missing utilityId `false`"
(anonymous) @ aura_prod.js:890
aura_prod.js:812 Uncaught (in promise) Error: Invalid or missing utilityId `false`

What's worse, just for having attempted to use the Utility API in the init method appears to disable it permanently in my utility bar component, as the button starts logging the same error on the Chrome console and no longer functions.

But if I comment out the line of code in the doInit method ("utilityAPI.setUtilityLabel({label: 'Salesforce Utility Label'});"  then the button will work just fine.


 
I have a record edit form that works for me, but "rarely" works for another user (I'm logging in as that user to test this) -- but here's the kicker -- *until* they go do other stuff and come back later.

The lightning component consists of a lightning:recordEditForm that has several fields including about 4 lookup fields (Account, Contact, managed obj Vehicle Inventory and managed obj Location). One of the lookups is to a custom object, and gets a default value based on the user's settings. When creating a new record, the default value shows up properly. The record is saved and that location lookup value is in the record -- it's visible in the "Recent items" related list.  But when this user re-opens the record that value isn't there anymore. 

When the value will NOT display on-screen I'm seeing an error 4 times in my Chrome consols: "Cannot read property 'color' of undefined.'  This error occurs *between* the completion of my "init" handler and the start of the RecordEditForm's onload method. The "setDefaultLocation" routine runs correctly when initiating a new record, but does not run (and shouldn't) when displaying an existing record with the value specified.

I've verified that the user has read & edit authority on all fields in the object and can read the target object of the lookup field. And again, if I log off as this user, then log in as this user again (or just go on to other things and come back later), then the lookup field is properly displayed.

I think the full code is too much for the forum, but here are some snippets:

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,force:appHostable,lightning:actionOverride"
    controller="RentalAgreementLex">
...
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
...
<lightning:recordEditForm recordId="{!v.recordId}" objectApiName="dealer__Rental_Agreements__c"
    aura:id="newrecordform" onsuccess="{!c.recordSaved}" onerror="{!c.recordSaveError}"
    onload="{!c.pageload}">
...
            <lightning:inputField fieldName="Location__c" disabled="{!v.alreadyposted}" aura:id="location"
                required="true" readonly="{!v.alreadyposted}" class="mw_required"/>


Some of the controller code:
/* general page initializations */
    doInit : function(component, event, helper) {
        console.log('doInit');
        // initialize that we're not in the process of posting
        component.set("v.posting", false);
...
        console.log('doInit complete');
    },
    /* initializations when recordeditform is loaded */
    pageload: function(component, event, helper) {
        console.log('pageload');
        let id = component.get("v.recordId");
        console.log(id);
        let sts = (id==null) ? null : component.find("agreement_status").get("v.value");
        if (id==null) {
            sts = 'Open';   // default value
            let stscmp = component.find("agreement_status");
            if (stscmp!=null) stscmp.set("v.value", sts);
            component.set("v.status", sts); // also init record data status
            component.find("deposit_amount").set("v.value",0.00);   // default value
            component.find("excess_miles_charge").set("v.value",0.00);  // default value
            component.set("v.title","New Rental Agreement");
            component.find("totalperdiemtax").set("v.value",0.00);  // default value
            component.find("sales_tax").set("v.value",0.00);    // default value
            component.find("countysalestax").set("v.value",0.00);   // default value
            component.find("citysalestax").set("v.value",0.00); // default value
            component.find("thirdtierrentaltax").set("v.value",0.00);   // default value
        }
        // in doInit: component.set("v.title", name);
        let isopen = sts!='Paid';
        let posting = component.get("v.posting");
        console.log('isopen = ' + isopen);
        // enable/disable buttons based on rental status
        if (!posting && isopen) component.find("submitbutton").set("v.disabled", false);
        if (!posting && id!=null && isopen) component.find("postbutton").set("v.disabled",false);
        let fromaccount = component.get("v.fromaccount");
        if (fromaccount!==null) {
            component.find("account").set("v.value",fromaccount);
            helper.rtvPersonContactId(component, event);
        }
        let fromcontact = component.get("v.fromcontact");
        if (fromcontact!==null) {
            component.find("contact").set("v.value",fromcontact);
            helper.rtvContactsAccountId(component, event);
        }
        if (isopen) component.set("v.alreadyposted", false);
        else component.set("v.alreadyposted", true);
        // set default location
        let c_location = component.find("location");
        let location = null;
        if (c_location!=null) location = c_location.get("v.value");
        if (id==null && location==null) helper.rtvUserDefaultLocation(component, event);
        // initialize running totals
        helper.recalcTotals(component, event);
        console.log('pageLoad complete');
    },
 
I'd like to be able to iterate over all the lightning:inputfield components within a lightning:recordeditform. I've seen examples where all the form elements are given the same aura:id="formfield" and then using component.find("formfield"), but I also need to retrieve specific field values and so I've assigned a unique aura:id to each field to accomodate that need.

Is there a way to get a list of all the input fields within the form?
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 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.
Hi, I am writing a trigger that checks a checkbox field in the contact object after calculating the primaryContact, The primaryContact is the contact who has the most commissions, there is one primary contact per account. My code is able to chose a primary contact but it doesnt seem to update the value of the checkbox to true? This is what I have so far: 
trigger primaryContact on Commision__c (after insert, after update) {
    List<Account> accToCon = [SELECT Id,
                              (SELECT Id, Name, Total_Commission__c FROM Contacts) FROM Account];
    
    for(Commision__c com : Trigger.New){
        for(Account c: accToCon){
            Contact primaryContact;
            if(!c.Contacts.isEmpty()){
                primaryContact = findMaxCommission(c.Contacts);
                System.debug(primaryContact);
                togglePrimaryContact(c.Contacts, primaryContact.id);
            }
            else{
                continue;
            }
        }
    }
    
    Contact findMaxCommission(List<Contact> contacts){ 
        Contact chosenContact = contacts[0];
        Decimal max = contacts[0].Total_Commission__c;
        for (Contact i : contacts) { 
            if (max < i.Total_Commission__c) { 
                max = i.Total_Commission__c; 
                chosenContact = i;
            } 
        } 
        return chosenContact; 
    } 
    
    void togglePrimaryContact(List<Contact> contacts, id primaryContactId){
        for(Contact i : contacts){
            if(i.id == primaryContactId){
                i.Primary__c = true;
            }
            i.Primary__c = false;
        }
    }
}
any help would be greatly appreciated! thanks
 
Good day. How can I cover the catch clock with my current class. I'm stuck at 96% code coverage.
public with sharing class AccOppRecalcHelperClass {
    
    //this method which will be called in the trigger
    public static void opportunityTriggerMethod(List<Opportunity> oppList, Map<Id,Opportunity> oldOpp){
        
        //instantiate a list of ID's to store id's of account records
       List<id> accId = new List<id>();
        //instantiate a list of accounts
       List<account> acc = new List<account>();
        //initialize string variable closedWon to Closed Won stage field value stored in custom label
        String Closed_Won = Label.Closed_won;
        //initialize string variable closedLost to Closed Lost stage field value stored in custom label
        String Closed_Lost = Label.Closed_lost;
        String oldaccstat;
        String acctstat;
        Integer oppClosedLost = 0;
        Integer oppClosedWon = 0;
        
        //checks opportunity records from opportunity list
       for(Opportunity opp: oppList){
          //checks if account related to opportunity field is not empty
           if(opp.AccountId != NULL){
               //adds account ID related to opportunity record to list of ID's
               accId.add(opp.AccountId); 
           }
             
       }
        for (Opportunity oppRec : [SELECT Id, Name, StageName FROM Opportunity WHERE AccountId IN :accId AND StageName != NULL]){
            if( oppRec.StageName == Closed_Won){
                oppClosedWon++;
               
            }
            else if (oppRec.StageName == Closed_Lost){
                oppClosedLost++;
            }
        }
        for (Account myAccount : [SELECT ID, Number_of_Opportunities_Won__c, Number_of_Opportunities_Lost__c FROM Account WHERE ID in :accId ]){
            
                myAccount.Number_of_Opportunities_Won__c = oppClosedWon;
                myAccount.Number_of_Opportunities_Lost__c = oppClosedLost;
                acc.add(myAccount);
            
        }
            
        if (acc.size()>0){
            try{
               update acc; 
            }
            catch(Exception e){
                System.debug(e);
            }
        }
        
    } 
}
This is my test class


 
@isTest
public class AccountOpportunityRecalculationTest {
  
private static testMethod void updateStage(){
    User sysAd = [SELECT Id,Name FROM User WHERE FirstName = 'Sherwin'];
      System.runAs(sysAd) {
         // The following code runs as System Administrator.
         Account[] accts = TestDataFactory.createAccountsWithOpps(1, 1, 'Closed Won');
         // The following code runs as user in Marketing Group.
         User MarketingUser = [SELECT Id,Name FROM User WHERE FirstName = 'Mario'];
         Test.startTest();
          try {
              System.runAs(MarketingUser) {
                    // Query for the opportunity, which has been associated with an account.
                    Opportunity opportunityToUpdate = [SELECT StageName FROM Opportunity 
                                                       WHERE StageName = 'Closed Won' ORDER BY LastModifiedDate DESC NULLS FIRST LIMIT 1];
                  // Update the billing city.
        			opportunityToUpdate.StageName = 'Closed Lost';
                  // Make the update call.
        			update opportunityToUpdate;
                  	System.assertEquals('Closed Lost', opportunityToUpdate.StageName , 'Expected opportunity with Closed Lost stage name');
              }
          
		} catch(Exception e) {
    		System.debug('An unexpected error has occurred: ' + e.getMessage());
	}         	
         }
         Test.stopTest();
        }
}
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?
 
Hello All,

I have a requirement like in each account record there is a amount field, i would like to SUM of total amount & store into the ultimate parent.

As of nw, i can able to get ultimate parent using trigger but i dont knw how to traverse from ultimate to child levels.

Regards,
VSK98
 
  • June 22, 2020
  • Like
  • 0
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
 
Hello, I'm very new to Salesforce and Apex (about 2 weeks), so I'm still learning the basics and terminology.

I've been given a sandbox (Developers type, I'm told) and asked to create a batch class to process a large number of records. The problem I'm having is that there are already triggers defined on the object I'm working with, so when I run my batch job, those triggers run into the non-batch limits and cause it to fail. So I'd like to edit or delete those triggers. However, they are part of a managed package that was installed as part of the sandbox, so I can't touch them. I can uninstall the whole managed package, but that would make the sandbox worthless for development, since I need those objects, just not the trigger.

Is there a way around this I'm not seeing, that would allow me to disable or edit a trigger in a managed package in a sandbox? Should I have a different kind of sandbox for this sort of work? Thank you.
I am trying to map over a checkbox from lead to dealer. I spoke with Saleforce support and their suggestion was code creation but unfortunately couldn't help with that. They said to ask on this forum for developer support. Can anyone help? Thank you!! 
I need to access sforce.one in javascript inside a visualforce page that I'm including in a lightning component via iframe.

If I use the native "VisualForce" component then sforce.one is defined for me. But I'm short on vertical space and don't want to waste any on an extraneous title line and also I need to control the iframe height dynamically. So I created a simple component that includes the VF page in my own iframe, but sforce.one is NOT defined when I do it that way.

 
I have a record edit form that works for me, but "rarely" works for another user (I'm logging in as that user to test this) -- but here's the kicker -- *until* they go do other stuff and come back later.

The lightning component consists of a lightning:recordEditForm that has several fields including about 4 lookup fields (Account, Contact, managed obj Vehicle Inventory and managed obj Location). One of the lookups is to a custom object, and gets a default value based on the user's settings. When creating a new record, the default value shows up properly. The record is saved and that location lookup value is in the record -- it's visible in the "Recent items" related list.  But when this user re-opens the record that value isn't there anymore. 

When the value will NOT display on-screen I'm seeing an error 4 times in my Chrome consols: "Cannot read property 'color' of undefined.'  This error occurs *between* the completion of my "init" handler and the start of the RecordEditForm's onload method. The "setDefaultLocation" routine runs correctly when initiating a new record, but does not run (and shouldn't) when displaying an existing record with the value specified.

I've verified that the user has read & edit authority on all fields in the object and can read the target object of the lookup field. And again, if I log off as this user, then log in as this user again (or just go on to other things and come back later), then the lookup field is properly displayed.

I think the full code is too much for the forum, but here are some snippets:

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,force:appHostable,lightning:actionOverride"
    controller="RentalAgreementLex">
...
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
...
<lightning:recordEditForm recordId="{!v.recordId}" objectApiName="dealer__Rental_Agreements__c"
    aura:id="newrecordform" onsuccess="{!c.recordSaved}" onerror="{!c.recordSaveError}"
    onload="{!c.pageload}">
...
            <lightning:inputField fieldName="Location__c" disabled="{!v.alreadyposted}" aura:id="location"
                required="true" readonly="{!v.alreadyposted}" class="mw_required"/>


Some of the controller code:
/* general page initializations */
    doInit : function(component, event, helper) {
        console.log('doInit');
        // initialize that we're not in the process of posting
        component.set("v.posting", false);
...
        console.log('doInit complete');
    },
    /* initializations when recordeditform is loaded */
    pageload: function(component, event, helper) {
        console.log('pageload');
        let id = component.get("v.recordId");
        console.log(id);
        let sts = (id==null) ? null : component.find("agreement_status").get("v.value");
        if (id==null) {
            sts = 'Open';   // default value
            let stscmp = component.find("agreement_status");
            if (stscmp!=null) stscmp.set("v.value", sts);
            component.set("v.status", sts); // also init record data status
            component.find("deposit_amount").set("v.value",0.00);   // default value
            component.find("excess_miles_charge").set("v.value",0.00);  // default value
            component.set("v.title","New Rental Agreement");
            component.find("totalperdiemtax").set("v.value",0.00);  // default value
            component.find("sales_tax").set("v.value",0.00);    // default value
            component.find("countysalestax").set("v.value",0.00);   // default value
            component.find("citysalestax").set("v.value",0.00); // default value
            component.find("thirdtierrentaltax").set("v.value",0.00);   // default value
        }
        // in doInit: component.set("v.title", name);
        let isopen = sts!='Paid';
        let posting = component.get("v.posting");
        console.log('isopen = ' + isopen);
        // enable/disable buttons based on rental status
        if (!posting && isopen) component.find("submitbutton").set("v.disabled", false);
        if (!posting && id!=null && isopen) component.find("postbutton").set("v.disabled",false);
        let fromaccount = component.get("v.fromaccount");
        if (fromaccount!==null) {
            component.find("account").set("v.value",fromaccount);
            helper.rtvPersonContactId(component, event);
        }
        let fromcontact = component.get("v.fromcontact");
        if (fromcontact!==null) {
            component.find("contact").set("v.value",fromcontact);
            helper.rtvContactsAccountId(component, event);
        }
        if (isopen) component.set("v.alreadyposted", false);
        else component.set("v.alreadyposted", true);
        // set default location
        let c_location = component.find("location");
        let location = null;
        if (c_location!=null) location = c_location.get("v.value");
        if (id==null && location==null) helper.rtvUserDefaultLocation(component, event);
        // initialize running totals
        helper.recalcTotals(component, event);
        console.log('pageLoad complete');
    },
 
One of our users has created a list view for her activities that was too vague and it is returning too many results, which is resulting in her Activities tab timing out and makes it unable to load the page at all. (Note: this is not just for one list view on activities page, but the whole Acitivites page itself)

I've had experience with this before, but I was always able to load the main landing page for Activities and resolve using this article <https://help.salesforce.com/articleView?id=How-do-I-fix-an-activity-list-view-that-is-timing-out-1327365102712&language=en_US&type=1>. However, since I am unable to even open her Activities tab, I cannot use this method. 

The error I get: "Time limit exceeded Your request exceeded the time limit for processing" 

I had opened a case up with SFDC support, but they won't help me because it is a visual force page. 

Thank you, and please let me know if I can provide you with any other helpful info. 

-Annemarie
Part of this is me struggling with the syntax and the other part is me not knowing what system method to use. A decimal method, math method?

Code:
Decimal parentlistPrice = 9995.00
Decimal svcPercent = .17
Decimal discount = .88
//oli.quantity = 2.0
        
oli.TotalPrice = ((parentListPrice * svcPercent) * discount) * oli.Quantity;

oli.TotalPrice  will equal 2990.504 but I would like to round this to only two decimal places so the value is 2990.50
 

  • September 05, 2008
  • Like
  • 0