+ Start a Discussion
SriniSrini 

Need help for validation rule:

Hi Team,

Is there any possible to create a validation rule for stoping task creation when Opportunity stage = completed ?. If yes please help us.

Thanks in Advance

 
Swaraj Behera 7Swaraj Behera 7
Hi Srini,
Can you please use below trigger which will act as a validation rule.Let me know if you find any isssue.
trigger TaskSubject on Task (before insert) {

    Task[] tasks = Trigger.new;
   

    for (Task t :tasks) {

           if (t.Whatid !=null) {

           	string tempId = string.valueOf(t.WhatId);

           	if(tempId.startsWith('006'))
           	{
           		opportunity opp= [Select id,StageName from opportunity where id=:t.Whatid];

           		if(opp.StageName=='Completed')
                 		a.addError('You can not add a task on opportinty if the status is Completed ');

           		 }
           	}        
        }
}

Thanks,
Swaraj Behera
Amit Chaudhary 8Amit Chaudhary 8
Hi Srini,

You Can write Trigger validation for same. But please dnt use SOQL inside the For loop

You can try below code.
 
trigger TaskTrigger on Task (before insert)
{

    Set<ID> setOppId= new Set<Id>();
    
    for ( Task t : Trigger.new )
    {
        if (t.Whatid !=null)
        {
               string tempId = string.valueOf(t.WhatId);
               if(tempId.startsWith('006'))
               {
                setOppId.add(t.Whatid);
            }    
        }
    }
    
    if(setOppId.size() > 0 )
    {
    
        Map<Id,opportunity> mapOpp = new Map<Id,opportunity>( [Select id,StageName from opportunity where id=:setOppId ] );
        for ( Task t : Trigger.new )
        {
            if ( t.Whatid !=null && mapOpp.containsKey(t.Whatid) )
            {
                opportunity opp = mapOpp.get(t.Whatid);
                
                if(opp.StageName=='Completed')
                {
                    t.addError('You can not add a task on opportinty if the status is Completed ');
                }
            }
        }    
    }
}


1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers

4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail

Let us know if this will help you

 
SriniSrini
Hi Amith,

But my requirement is whenever opty fields are update task should be crate automatically, the same time if opty was closed task should not create.

For that we have written on trigger : is working as expected but i want to stop the task create when opty is closed.Please find the Below trigger and let us know where i needs to be change.

trigger UpdateTask on Opportunity (after insert, after update,before insert) {
    
    List<Opportunity> listOpp = Trigger.new;
    List<Task> listTask = new List<Task>();
    if(Trigger.isInsert) {
        for(Opportunity opp:listOpp) {
            if(opp.Helps__c != null && opp.StageName == 'Closed Won'){
                Task t = new Task();
                t.OwnerId = opp.OwnerId;
                t.WhatId = opp.Id;
                t.Subject ='Help' + ': ' +opp.Helps__c + ': '  + opp.Name; 
                //t.ActivityDate = opp.Helps__c;
                t.ActivityDate = System.Today()+7;  
                t.Description = opp.Description__c;
                t.Status = 'In Progress';
                t.Priority = 'Normal';
                listTask.add(t);
            } else{
                opp.addError('not update');
                }
        }
    }

Please help me on this

Thanks
Swaraj Behera 7Swaraj Behera 7
Hi Srini,
Please change opp.Stagename != 'Closed Won' in the if condition.

Thanks