0

I am trying to pull values from a query result I'm performing on the Product2 sObject and am trying to save the values from the query into individual variables.

My query result:

|DEBUG|product_query: (Product2:{ProductCode=88-7799, Id=01t1U000009Uf2IPGS})

I have tried using internal_product_code = product_query.get('ProductCode') but am unable to pull any of the values out. I keep getting the following error Method does not exist or incorrect signature: void get(String) from the type List<Product2>. Is there another way to access this value?

product_query = [Select ProductCode 
                                     From Product2
                                     Where Name = :current_sensor];

                    System.debug('product_query: ' + product_query);

                    String internal_product_code = product_query.get('ProductCode');

1 Answer 1

2

I would suggest going through the Apex developer guide once.

As to answer your question, it depends on the variable type. I think yours is the second case.

Case 1

If your query looks like this :

Product2 product_query = [Select ProductCode From Product2 Where Name = :current_sensor];

then the result accessed via (You will get QueryException if more than one record is returned)

String internal_product_code = product_query.ProductCode;

or via casting the result to SObject and then using get methods of SObject class.

String internal_product_code = ((SObject) product_query).get('ProductCode');

Case 2

If your query looks like this

List<Product2> product_query = [Select ProductCode From Product2 Where Name = :current_sensor];

then you will have to iterate over the list

for(Product2 productRecord: products_query){
// Do something here
String value = productRecord.ProductCode
}

or you can access the value directly based on the index.

if(!product_query.isEmpty()){
String productCode = product_query.get(0).ProductCode
}
1
  • Thank you for all your help
    – Richard
    Mar 25, 2020 at 22:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.