Hi Everyone I'd like to post my very first question on Salesforce Apex and ask for any help on this. What I'm looking for here is guidance on how to proceed on querying data from OpportunityLineItem Object programmatically.
My end goal is to copy a value from a custom field under Product to a custom text field in Opportunity. During my research I got to know that the link between Opportunity and Product happens through OpportunityLineItems which links the two Obejects. (This is my understanding based on googling stuff)
In the code below I'm setting the values for OpportunityLineItems - OpportunityId and Product2ID in a way that I'd know it was working for the scenario I have. Here's the code to list Opportunities with Product with Practice field(at least it was the plan...):
public with sharing class UpdatePracticeOnOpportunity {
//Method to get opportunities that have products associated to it
public List<OpportunityLineItem> getAllOppsWithPractice() {
String OppId = '0064x0000037gMqAAI';
String Prod2Id = '01t4x00000164W8AAI';
//Receives OLIS values
List<OpportunityLineItem> OppWithPractice = new List<OpportunityLineItem>([SELECT id, name, OpportunityId, Product2Id
FROM OpportunityLineItem]);
// WHERE PRODUCT2.ID = :Prod2Id AND OPPORTUNITY.ID = :OppId
return OppWithPractice;
}
}
Here's the class I'm using to run Apex Tests
@IsTest
public with sharing class UpdatePracticeOnOpportunityTest {
@IsTest
static void should_update_opportunity() {
//Test.startTest();
UpdatePracticeOnOpportunity upOppPractice = new UpdatePracticeOnOpportunity();
//Test.stopTest();
upOppPractice.getAllOppsWithPractice();
}
For some reason both queries are returning nothing, however running the same query via SOQL it does return rows. What am I missing here? This code was run in two different Orgs but had the same result.
Here's the results of a query run using SOQL on Visual Code
SELECT id, name, OpportunityId, Product2Id FROM OpportunityLineItem
|ID | NAME | OPPORTUNITYID | PRODUCT2ID
────────────────── ───────────────────────────────────────────────── ────────────────── ──────────────────
|00k5A00000r6ftzQAA| Edge Installation GenWatt Diesel 1000kW | 0065A00000n4bIFQAY | 01t5A000008OOn3QAG
|00k5A00000r6ft6QAA| Dickenson Mobile Generators GenWatt Diesel 1000kW| 0065A00000n4bI0QAI | 01t5A000008OOn3QAG
Running code as SFDX: Execute Anonymous Apex with Currently Selected Text
19:24:00.11 (19609255)|VARIABLE_ASSIGNMENT|[3]|OppWithPractice|[{"Id":"00k4x00000gD7zrAAC","Name":"Burlington Textiles (45 more) ...","OpportunityId":"0064x0000037gMqAAI","Product2Id":"01t4x00000164W8AAI"}]|0x6e0f8062
19:24:00.19 (19688432)|CUMULATIVE_LIMIT_USAGE
19:24:00.19 (19688432)|LIMIT_USAGE_FOR_NS|(default)|
Number of SOQL queries: 1 out of 100
Number of query rows: 1 out of 50000
References:
public with sharing class UpdatePracticeOnOpportunity {