function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jia Kang WonJia Kang Won 

how to add product(lookup) to Account with apex

I want a Apex code to add product from lookup list to my account.
Any idea??
Best Answer chosen by Jia Kang Won
BALAJI CHBALAJI CH
Hi Jia Kang Won,

Since Product__C is a lookup field, you have set Product Id to that lookup field. BEfore that you need to query the required Product.
Try below sample code:
trigger mycustomize on Account (before insert, before update) {
    for(Account acc : Trigger.new) {
        acc.Type = 'Prospect';
        Product2 product = [select id, name from product2 where name= 'GenWatt Diesel 200kW' limit 1];
        acc.Product__c= product.id;
    } 
}

Note: This is just sample code to add Productwith a particular name to Account. The code should be bulkified as per the requirement.

Let us know if that helps you.

Best Regards,
BALAJI

All Answers

Jia Kang WonJia Kang Won
// i am start with this
trigger mycustomize on Account (before insert, before update) {
    for(Account acc : Trigger.new) {
        acc.Type = 'Prospect';
    
     //acc.Product__c= 'GenWatt Diesel 200kW';
    
    }
    
    
    
   
}
BALAJI CHBALAJI CH
Hi Jia Kang Won,

Since Product__C is a lookup field, you have set Product Id to that lookup field. BEfore that you need to query the required Product.
Try below sample code:
trigger mycustomize on Account (before insert, before update) {
    for(Account acc : Trigger.new) {
        acc.Type = 'Prospect';
        Product2 product = [select id, name from product2 where name= 'GenWatt Diesel 200kW' limit 1];
        acc.Product__c= product.id;
    } 
}

Note: This is just sample code to add Productwith a particular name to Account. The code should be bulkified as per the requirement.

Let us know if that helps you.

Best Regards,
BALAJI
This was selected as the best answer
Jia Kang WonJia Kang Won
Hi BALAJI,

That is i want and work fine to me. 
Appreciate fast respone and correct answer.

Thanks a lot, itwas help me
BALAJI CHBALAJI CH
Great to hear that. :-)
You can close the thread by marking Best Answer so that it can be helpful to someone else.
Have a Nice Day.