You need to sign in to do that
Don't have an account?
tomasdd
Trigger question - date field clear
Hi all,
I have to write a trigger to clear date field when date is today.
So let's say we have date field called 'abc' and date for 'abc' is 24.06.2019 when today's date will be 24.06.2019 field 'abc' should be automatically clear.
Which function should I use to achieve this ? Before update, after insert ?
An interesting requirement.
To answer the first part of your question - it depends on where is the trigger to be fired from?
If we are update the record via the UI, then I would do a trigger on the Object as a ( before Insert , before Update). This is due to if we are editing the record and do an after update, we risk the trigger being triggered into a loop. Remember, each DML (write) would trigger the After Update trigger - which writes to the record and then invokes the After update Trigger - which.... i think you get the idea.
If we are clearing the date field in a related object, then the After Trigger comes into play.
Note - a trigger fired from the object will not clear the field if the record is not edited on the day of the date field.
If the requirement is to clear the date field when the date passes, then you need to look at batch Apex jobs. Or Time based Work Flows.
Regards
Andrew
All Answers
An interesting requirement.
To answer the first part of your question - it depends on where is the trigger to be fired from?
If we are update the record via the UI, then I would do a trigger on the Object as a ( before Insert , before Update). This is due to if we are editing the record and do an after update, we risk the trigger being triggered into a loop. Remember, each DML (write) would trigger the After Update trigger - which writes to the record and then invokes the After update Trigger - which.... i think you get the idea.
If we are clearing the date field in a related object, then the After Trigger comes into play.
Note - a trigger fired from the object will not clear the field if the record is not edited on the day of the date field.
If the requirement is to clear the date field when the date passes, then you need to look at batch Apex jobs. Or Time based Work Flows.
Regards
Andrew
Let us take an example with opportunity Date_For_Test__c custom field and for your requirement, you can use both functions before update, before insert as if you will insert a record with today's date then it will be automatically cleared and if you will update a record with today's date then it will be also automatically cleared.
try below code:
trigger: I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi