Jun 8, 2011

Change Unit Status automatically after 48 hours

Starting my blogs on Salesforce.com tips n tricks.. 
This one is based on my post from discussion board.

Use case: Unit is a custom object. Opportunity has a lookup(Unit Code) to it. Unit has a picklist field - Unit Status, with values 'Available', 'Blocked', 'Sold'. When the Opportunity Stage is Blocking, the corresponding Unit's status should change to 'Blocked' and after 48 hours if the Stage is not changed to next stage(Closed Won), Unit Status must be changed to 'Available'.

Solution(according to me):
  • Create a picklist field 'Set the Unit Status' on Opportunity with values - Available and Blocked
  • Create 3 workflows
    • To change the value of 'Set the Unit Status' to blocked if user selects a Unit. (Rule action)
    • To change the value of 'Set the Unit Status' to  available if user doesn't change opportunity stage after 48 hours. (Rule & action)
    • To change 'Set the Unit Status' to blank.
These workflows will change the Opportunity picklist(Set the Unit Status) value. Based on the change in value a trigger will update the corresponding Unit's status. Here is the code:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
trigger OpptyTrigger on Opportunity (before insert, before update) {
    Map<id,string> unitDetails = new Map<id,string> ();
    for(Opportunity O : Trigger.New) {
        if(O.Set_the_Unit_Status__c != null) {
            if(O.Set_the_Unit_Status__c.equals('Blocked'))
                unitDetails.put(O.Unit__c,'Blocked');
            else if(O.Set_the_Unit_Status__c.equals('Available'))
                unitDetails.put(O.Unit__c,'Available');
         }
    }
    System.debug('#### unitDetails: ' + unitDetails);
    List<Unit__c> lstUnits = [select Unit_Status__c from Unit__c where 
                        Id IN: unitDetails.keySet() ];
    System.debug('#### lstUnits(before): ' + lstUnits);
    for(Unit__c U : lstUnits) {
        U.Unit_Status__c = unitDetails.get(u.Id);
    }
    System.debug('#### lstUnits(after): ' + lstUnits);
    update lstUnits;
}

Tested this trigger and it is working fine.

I posted on discussion board just to check whether there is any better/easier solution. This is not THE ONLY solution for similar use-cases. If you have any suggestion to modify the code I will be grateful to look into it.

Featured Post

I am Salesforce Certified System Architect

By passing Identity & Access Management Designer, I earned System Architect. The journey of Application Architect & System Architec...

Popular Posts