Showing posts with label triggers. Show all posts
Showing posts with label triggers. Show all posts

Button to activate/deactivate a task on a object

Sometimes we feel like to create a button/checkbox to activate/deactivate a task on that respective object. There are two ways to do that
1) Workflows (Easier, but has limits)
2) Trigger
I am sharing the code with you for creating a checkbox. If set to true, create a task for reminding after 30 days, if deactivated, delete the task.

for (Contact c :trigger.new){

  contact oldc = trigger.oldmap.get(c.id);

  if(c.Activate__c==true && oldc.Activate__c==false){

    task t = new task();

    t.subject = 'Reminder about calling Contact';

    t.whoid = c.id;

    t.isreminderset = true;

    t.reminderdatetime = system.today()+30;

    t.status = 'In Progress';

    t.IsRecurrence = false;

    insert t;}


  else if(c.Activate__c==false && oldc.Activate__c==true){

   List<task> t = [select id from task t where t.whoid=:c.id and t.subject='Reminder about calling Contact'];

   delete t;

  }} }

Controlling Recursive Triggers

Sometimes we need to update the record of same object, which is intializing the trigger. This will cause recursive trigger and throws an exception. Exception could be "SELF_REFERENCE_FROM_TRIGGER"
For example, suppose you have self look up to contact named spouse. You have two contact, A and B. when you select A as spouse of B, you want to also update A as spouse of B. In trigger for A, when you update B, it will call recursive trigger.
To control/prevent such condition, we need to add a static variable in another class, as this variable will share single instance, as these transaction has occured from a single event. This static variable allows the code to execute in first run. but prevent from any run thereafter.



code for static var:


public class flag {
public static boolean firstrun = true;
}

code for trigger:


trigger MatchSpouse on Contact (after insert, before update) {
List spouses = new List();
Contact spouse;
for (Contact c : Trigger.new){
if (c.Spouse__c != null){
spouse = new contact(id = c.spouse__c);
if(spouse.Spouse__c != c.id)
{
spouse.Spouse__c = c.id;
spouses.add(spouse);
}}}
if(spouses.size()>0 && flag.firstrun ){
flag.firstrun = false;
update spouses;

}}