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
CB IT Support - RobinCB IT Support - Robin 

How do I write a trigger to update fields to null when criteria is met?

I am not a developer - not even close. I have a request to update fields to null when criteria is met and one of the fields is a multi-select picklist and I'm having a hard time accomplishing this request with workflow/field update or Process Builder. I believe this could be accomplished with a trigger but I know nothing about them. I have googled triggers and I've attempted to write one and I know it won't work as-is but maybe it will shed some light on what I'm trying to do. The request is: if the record type = 'x' and the record owner is changed to 'x', then set the status to Active and set the other 3 fields to null. 

for (Lead l : Trigger.new) {
 if (l.RecordTypeId = '012V00000008yPS' &&
     l.OwnerId = '00500000006xlI8')
    l.LeadStatus = 'Active';
    l.Blitz_Yield_Disposition__c = null;
    l.Blitz_Yield_Disposition_Reason__c = null;
    l.Blitz_Yield_Month__c = null;
     update l;
}
 
Hemant_SoniHemant_Soni
Hi CB,
Try below code for trigger.
trigger Lead on Lead (Before Insert,Before update) {
	list<Lead>lstLead = new list<Lead>();
if(trigger.isBefore){
system.debug('@developer-->IsBefore');
if(trigger.IsInsert || trigger.IsUpdate){
	RecordType rtLead = [select id,name,developername from recordtype where sObjecttype='Lead' and developername='YOUR_RecordTypeName'];
	for(Lead oLead:trigger.new){
		
		if(oLead.RecordtypeId == rtLead.Id && (oLead.OwnerId != trigger.oldmap.get(oLead.Id).ownerId && oLead.OwnerId == 'YOUR OwnerId')){
		Lead l = new Lead();
		l.RecordtypeId = rtLead.Id;
		l.LeadStatus = 'Active';
		lstLead.add(l);
 	}
}
if(lstLead.size()>0){
update	lstLead;
}	
}
}
And make changes according to your requirement.
If it helps please mark it solved.
Thanks
Hemant
 
Davy HuijgensDavy Huijgens
Hi Robin, a couple of things you need to change:

1. You do not check if the recordowner is changed in your posted code.
2. You should bulkify your code.
3. at this point only the update if the leadstatus field is dependant on your if statement
 
List<Lead> toUpdate = new List<Lead>();

for (Lead l : Trigger.new) {
    if (l.RecordTypeId ==  '012V00000008yPS' && l.OwnerId ==  '00500000006xlI8' && l.OwnerId != Trigger.oldMap.get(l.Id).OwnerId){
        l.LeadStatus = 'Active';
        l.Blitz_Yield_Disposition__c = null;
        l.Blitz_Yield_Disposition_Reason__c = null;
        l.Blitz_Yield_Month__c = null;
        toUpdate.add(l);
    }
    update toUpdate;
}

Syntax could be slightly if but this will get you there in a code editor.

If this helps you solve your issue please mark it as the best answer.