You need to sign in to do that
Don't have an account?
Victor P
Trigger that writes all Products in a custom field at Opportunity object level
Hi all,
I'm trying to create a trigger on the Opportunity object to write all Products of said Opportunity in a custom field.
I found how to do this in an Apex class but it looks like Apex triggers are using a different language?
I'm trying to create a trigger on the Opportunity object to write all Products of said Opportunity in a custom field.
I found how to do this in an Apex class but it looks like Apex triggers are using a different language?
trigger OpportunityConcatenation on Opportunity (before insert, before update, after insert, after update, before delete) { var opp = new sforce.SObject("Opportunity"); opp.Id = '{!Opportunity.Id}'; result = sforce.connection.query("Select PricebookEntry.Product2.Name, Quantity, TotalPrice From OpportunityLineItem WHERE OpportunityId = '{!Opportunity.Id}' and (NOT Name like '%Discount%')"); records = result.getArray("records"); var strProductNames = ''; for(var i=0; i<records.length ; i++){ strProductNames += 'PRODUCT NAME: ' + records[i].PricebookEntry.Product2.Name + ' --- QUANTITY: ' + records[i].Quantity + ' --- TOTAL PRICE: $ ' + records[i].TotalPrice +',\n'; } if(strProductNames.length>0){ strProductNames = strProductNames.substring(0,strProductNames.length-2); } opp.Samples_Sent__c = strProductNames; sforce.connection.update([opp]); }
You should consider writing a trigger on OpportunityLineItem(OLI) instead of Opportunity. Whenever a product is added to an opportunity, a record is created in the OLI object. You should write a trigger on insert of OLI which will update the custom field present on parent opportunity record. OLI has lookup to Product, Pricebookentry and Opportunity, so you have all the information you need to update your custom field.
What's the downside? Not seeing when a new Product is created without updating the Opportunity? It sounds like way more complicated if I put it in the OpportunityLineItem object because I would have to first check if the Product already exists in the list and only add it if it isn't. Then I'd have to create something to remove Products that have been removed, etc.
2. With that opportunity id, query all the OLI already present under that opportunity. Loop through the result, each result item will have the product name. Keep concatinating the product names in a variable in the loop.
3. Replace the result in Samples_Sent__c field present on Opportunity.