Search code examples
triggerssalesforceapexsoql

Copy Product Price into a Custom Field Object using APEX Trigger in Salesforce


Trying to just copy the Cost_Price__c field of a product into a custom object when it is updated (if possible inserted too) using an APEX trigger.

I'm so close but the error I am getting at the moment is: Illegal assignment from PricebookEntry to String

trigger updateAccount on Account (after update) {
  for (Account oAccount : trigger.new) {
    //create variable to store product ID
    string productId = oAccount.Product__c;

    //SQL statement to lookup price of product using productID
    PricebookEntry sqlResult = [SELECT Cost_Price__c 
        FROM PricebookEntry 
        WHERE Product2Id =: productId];

    //save the returned SQL result inside the field of Industry - Illegal assignment from PricebookEntry to String
    oAccount.Industry = sqlResult;
  }     
}

Am I right in thinking it's because its returning a collective group of results from the SOQL call? I've tried using the sqlResult[0] which still doesn't seem to work.


Solution

  • The Illegal Assignmnet because you are assigning a whole Object i.e PriceBook Entry to a string type of field i.e Industry on Account.

    Please use the following code for assignment.

    oAccount.Industry = sqlResult[0].Cost_Price__c;

    Please mark the answer if this works for you.

    Thanks, Tushar