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
Harshi_PandeyHarshi_Pandey 

Update parent object field with Apex trigger in child object record

Hello Everyone,

I have a child object SoldProducts__c whose parent object is 
Warehouse__c as a lookup relationship. I want to update a field in object Warehouse__c known as In_Stock__c with the value in the field
In_Stock__c in the child object SoldProducts__c with the help of apex trigger.
Please find the screenshots below for your reference:

User-added imageUser-added image

I tried the below code but no luck :
 
trigger SoldProduct on SoldProducts__c (before insert)
	{
	
		string ItemName;
		if(trigger.IsInsert && trigger.IsBefore)
		{
				for(SoldProducts__c sp : Trigger.new){
          			
                    ItemName = sp.Items__c;
				}				
		 for(SoldProducts__c  opp: Trigger.new)
    	{     
            List<SalesStock_Items__c> ssi = new List<SalesStock_Items__c>();
			
            SalesStock_Items__c si = [Select Warehouse__r.In_Stock__c from SalesStock_Items__c where Name like :ItemName];          
            si.Warehouse__r.In_Stock__c = opp.In_Stock__c;
            
			ssi.add(si);
            update ssi;
        }
		}
	}

Can anyone please help me here.
Best Answer chosen by Harshi_Pandey
Suraj Tripathi 47Suraj Tripathi 47

Hi Harshi,

Please find the solution. "Update parent object field with Apex trigger in child object record".

If SoldProducts__c is child of Warehouse__c then we can update the In_Stock__c field of Warehouse__c Like this.

trigger SoldProduct on SoldProducts__c (After insert)
	{
		if(trigger.IsInsert && trigger.IsAfter)
		{
		List<Warehouse__c> WarehouseList=new List<Warehouse__c>();
				for(SoldProducts__c sp : Trigger.new){
          			Warehouse__c obj=new Warehouse__c();
					obj.id=sp.Warehouse__c;
					obj.In_Stock__c=sp.In_Stock__c;
                   WarehouseList.add(obj);
				}
             update 	WarehouseList;			
		 
		}
	}

I think no need to use this object SalesStock_Items__c. If you want to use this object SalesStock_Items__c then please explain your queries in detail.

Please let me know it is working or not.

If it works then Please Mark it as Best Answer so that other people would take reference from it.

Thank You!