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
naveen reddy 68naveen reddy 68 

Question on trigger

I have created a check box on the contact object,when ever i create a new record on contact the previous record checkbox field must be unchecked automatically
could some one help me ,how to write a trigger
Best Answer chosen by naveen reddy 68
Amit Singh 1Amit Singh 1
Hello Naveen,

If you want to update Contact which has that checkbox true whenever a new contact is being created. Means only one contact have checkbox is true. right?
 
use below code for the trigger.
trigger updateOldContact on Contact(before insert){
        List<Contact> conList = [Select Id, Name, CheckBox__c From Contact Where CheckBox__c = true];
        For(Contact con : conList){
            con.CheckBox__c = false;
        }
        For(Contact c: Trigger.New){
             c.CheckBox__c = true;
        }
        If(conList!=null && conList.size()>0)update conList;
}

Let me know if this helps :)

Thanks!
 

All Answers

Nishad KNishad K
Hi naveen,
Here you need to build a logic to find out the previous record in trigger.....

see the below example :

this example is not fit for bulk updates;
 
trigger updateCheckBox on contact (befor insert){

    list<contact>contactlist =new list<contact>();
    contactlist = [Select id, youCheckBox__c FROM contact Where  youCheckBox__c = true]; 
    for(integer i =0; i< contactlist.size();i++)
    {
        contactlist[i].youCheckBox__c = false;
    }

    update contactlist;

}

Regards;
Amit Singh 1Amit Singh 1
Hello Naveen,

If you want to update Contact which has that checkbox true whenever a new contact is being created. Means only one contact have checkbox is true. right?
 
use below code for the trigger.
trigger updateOldContact on Contact(before insert){
        List<Contact> conList = [Select Id, Name, CheckBox__c From Contact Where CheckBox__c = true];
        For(Contact con : conList){
            con.CheckBox__c = false;
        }
        For(Contact c: Trigger.New){
             c.CheckBox__c = true;
        }
        If(conList!=null && conList.size()>0)update conList;
}

Let me know if this helps :)

Thanks!
 
This was selected as the best answer