im trying setting an opportunity field with the name of a related product (there is always only one related product to each opportunity).

but , because im a new admin , im yet not fully control apex,

i though on trying OpportunityLineItems object (in an opportunity apex trigger) and form there get the connection

but i couldn't find the right code for using the LineItems on Opportunity controller.

could some one help me with the code, its very important for us.



1 Answer 1


You can use something like this:

    list<opportunity> lt = trigger.new[0];
list<opportunityLineItem> opli = new list<opportunityLineItem>([select id ,product2.name, opportunityId from opportunitylineitem where opportunityId =: trigger.new[0].id);
string productName='';
for(opportunityLineItem o : opli){
 productName = o.product2.name;
for(Opportunity opp : trigger.new){
 opp.custom_field__c = productName;
update lt;

Here, I am updating the custom_field__c in opportunity with a product name in the opportunity line items. Let me know if this helps.

  • hi man , thanx alot for the answer ( im both channels (: ) but, im getting an error - Compile Error: Illegal assignment from Opportunity to List<Opportunity> at line 3 column 20 (line 3 is first line in your code) thanx again
    – Oron M
    Jun 17, 2015 at 11:52
  • Use this line instead. This will solve your error. list<opportunity> lt = trigger.new; And please select as answer if it helps. Jun 17, 2015 at 12:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .