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

lookup field update using trigger

I have 2 custom object customobjt1__c and customobjt2__c, both have product lookup fields. 
If both product lookup field is the same then in customobjt1__c  we need to insert the record name of customobjt2__c that is also a lookup in customobjt1__c. so how to achieve that? 
AnudeepAnudeep (Salesforce Developers) 
Hi Nirdesh, 

The trigger will look something like this. This is just an example and you have to modify it accordingly
trigger MyTrigger on customobj2__c (before insert, before update) {
    Set<ID> productlookupcustomobjt2 = new Set<ID>();
    for (customobj2__c c : {
        if (c.product_lookup_customobjt2__c != null) {

    Map<Id, customobj1__c> customobjt1Map = new Map<Id, customobj1__c>([
            select Id, product_lookup_customobjt1__c
            from customobj1__c
            where product_lookup_customobjt1__c in :productlookupcustomobjt2

    for(customobj1__c c :customobjt1Map.values()) {
          //insert logic to insert the record name of customobjt2__c that is also a lookup in customobjt1__c.

    //Insert the object list

Thanks, Anudeep,
Actually, I need to write a trigger on Objc__1. 
objec__1 (Object) : Product1__c (Field)
Object__2 (Object): Product2__c (Field)
object__1 (Object): lookup3 (field)

if I hit on save in Object__1 and manually select  Product1__c (Field) then in object__1: lookup3 (field) field auto-populated., and that value should be Object__2 (Object)'s record id. 
Also, Need to check Product1__c  and Product2__c if both values are correct then only display lookup3  or error message display.
AnudeepAnudeep (Salesforce Developers) 
Hi Nirdesh,

Here is the code sample
trigger MyTrigger on objec__1(before insert, before update){ 
  Set<Id> prodIds = new Set<Id>();
  List<Object2__c> object2List = new List<Object2__c>();
for (Object o: {

object2List = [SELECT Product2__c FROM Object2__c WHERE Product2__c IN :prodIds];

Map<Id,Object2__c> prodInvMap = new Map<Id,Object2__c>();
for (Object2__c inv: object2List) {
    prodInvMap.put(inv.Product2__c, inv);
for (objec__1 o: {
    if (o.Product1__C == prodInvMap.get(o.Product1__C) ) {
        o.lookup3__c = prodInvMap.get(o.Product1__C);
    } else  {
        o.addError('Display error message here');
I hope the above code sample will point you in the right direction. If it does, please mark this answer as solved. Thank You!

Compile Error: Comparison arguments must be compatible types: Id, Product1__C  at line 15 column 8