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
Colby BridgesColby Bridges 

Trigger Help - No Task Creation

Ask: As a Sales Manager I would like to limit users ability to create tasks if an Opportunity has been closed for more than 4 days. 
As an Admin a Validation Rule doesn't seem like a viable solution. Trying to create a Trigger but running into some issues.

Problem - Line 5 - Inequality Operator not allowed for this type: Object
IF (a.WhatId!=null && String.valueOf(a.WhatId).startsWith('006')&& a.What.get('CloseDate') < (System.today()- 4) &&(RoleId =='00E800000029UCT'))
Trying to look at opp close date and evaluate if 4 days has past. If so, want to restrict ability to create tasks for certain role. 
Could someone help? Of if there is a better solution?


Trigger:
trigger NoTaskCreationForSE on Task (before insert) {
    String RoleId = UserInfo.getUserRoleId();
    for (Task a : Trigger.new)    
        
    IF (a.WhatId!=null && String.valueOf(a.WhatId).startsWith('006')&& a.What.get('CloseDate') < (System.today()- 4) &&(RoleId =='00E800000029UCT'))
        
    {
        a.addError('You Cannot Add Tasks Once An Opp Has Been Closed For More Than 4 Days');
    }
        
}

 
Pranav S SanvatsarkarPranav S Sanvatsarkar
Hello Colby,

Here are few suggestions from my side,
  • You should check for RoleId condition before the FOR loop
  • User the method - "OpportunityId".getSobjectType() instead of String.valueOf(a.WhatId).startsWith('006') as the suggested method will return API name of the object from the Id
Can you please share the error that is being thrown as the column number (character number) at line 5 is required to locate the expression causing the error.

Thanks.
Colby BridgesColby Bridges
Hi Pranav,
Thank you for your time.
The error is:
Problem - Line 5 - Inequality Operator not allowed for this type: Object

Line 5 = IF (a.WhatId!=null && String.valueOf(a.WhatId).startsWith('006')&& a.What.get('CloseDate') < (System.today()- 4) &&(RoleId =='00E800000029UCT'))
Pranav S SanvatsarkarPranav S Sanvatsarkar
Hello Colby,

Please try this code,
 
trigger TaskTrigger on Task (before insert) 
{
	Id allowedRoleId = '00E800000029UCT';
    if( UserInfo.getUserRoleId() == allowedRoleId )
    {
     	for( Task taskRecord : Trigger.New )
        {
            if( taskRecord.WhatId != null && taskRecord.WhatId.getSobjectType().getDescribe().getName() == 'Opportunity' && taskRecord.ActivityDate < (System.today() - 4 ) )
                taskRecord.addError('You Cannot Add Tasks Once An Opp Has Been Closed For More Than 4 Days');
        }
    }
}

Let me know if it works.

Thanks.​
Colby BridgesColby Bridges
Hello, 

Thank you for the updated code. It's still allowing user with that profile Id to create a task on the opportunity. I think I may need to include Stage = "Closed Won"? Or do I need to do a query?