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
Chidanand Magadum 24Chidanand Magadum 24 

Trigger to create a new record on the custom object when the status field of the Product object ischanged

Hi folks,

I wanna create a new record in my maintenance custom  object automatically when the status field of the standard Product object is changed to 'Out of maintenance'. So could any one please help me in writing trigger for the same. 
Waqar Hussain SFWaqar Hussain SF
trigger testTrigger on Product2 (after insert, after update) {
	for (Product2 p : {
		if(p.Status=='Out of maintenance'){
			Maintanance__c m = new Mantainance__C(Name='Out of maintenance', OtherFields=p.fields);
		insert m;


Frédéric TrébuchetFrédéric Trébuchet

Carefull, doing that you will have a new Maintenance__c record if Product status is 'Out of maintenance'.
If you want to have only one record where Product status change from any value to 'Out of maintenance', you have to get old Product status and continue only if it's different of 'Out of maintenance'.

Chidanand Magadum 24Chidanand Magadum 24
Here is my requirement,
If a user changes a product's status to Out for Maintenance, a new Maintenance History record should be created that is a child of the product. The from date should be today's date, the to date should be left blank.
When a user changes a product's status from Out for Maintenance to something else, Salesforce should find the most recent Maintenance History record for that product that has no "to" date, and set the to date to the current date.

Could anyone get me the right code for this requirement.
Bennie CloudyBennie Cloudy
Don't use Vickey's code it has a DML statement inside the for loop
Chidanand Magadum 24Chidanand Magadum 24
Hi Vicky, Your code is not working. It is not creating new New Record in my Maintenance custom object. Please help me with the correct code for my requirement.
rajesh k 10rajesh k 10
       Using trigger this is not possible.