I have an object in Salesforce
called File_uploaded__c
with some fields like Filename__c, fileSize__c, IsMain
, and I want to know if there's a way to implement a trigger that is only fired when we update the field IsMain
and not every time we update the whole object
1 Answer
You can do this by comparing the current value of the IsMain field with the value in the trigger.oldMap collection. This will tell you if the field has changed.
Something like this will work
trigger FileUploadedTrigger on File_uploaded__c (after update) {
list<File_uploaded__c> changedIsMainList = new list<File_uploaded__c>();
for(File_uploaded__c fu : trigger.new){
if(fu.IsMain__c != trigger.oldMap.get(fu.Id).IsMain__c){
changedIsMainList.add(fu);
}
}
//You now have a list of only those File_uploaded__c records where IsMain
//has changed. You can now perform your logic on only those records
//YOUR LOGIC HERE
}
This should get you started. I would also recommend reading through Apex Code Best Practices as well.
-
it's a good answer but every time i update some fields in my object the trigger will be fired even if it's not
IsMain
field and i wanna avoid that if it's possible– ihssanCommented May 26, 2015 at 13:56 -
1You cannot control the actual firing of the trigger itself. You can however, control which records within that trigger you take action on. The triggers for an object will always be fired when a record has DML performed on it. Commented May 26, 2015 at 13:58
-
This is a great answer and the article Chris linked is a great read as well - just out of curiosity, why do you want to prevent the trigger from firing at all? Commented May 26, 2015 at 14:05
-
Well, the field :
IsMain__c
is not the only one i will be updating, and when the trigger is fired it will only modify the fieldIsMain__c
– ihssanCommented May 26, 2015 at 14:15 -
1That is fine, but there is no harm in the trigger firing when the IsMain__c field is not changed. The trigger will basically do nothing as you will only be acting on records where that field did exist. Commented May 26, 2015 at 14:16
File_uploaded__c
shoud have One file as Main so when a user change another field as main the old main file shoud be set to false, but if he changes anther field like Filename or what ever the trigger shouldn't be fired