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
SriniSrini 

Scenarios help using trigger

Hi Team,
We have task,Whenever we entering in opportunity fields it should create a brand new task along with opportunity name.after creating automatic task it should assign some other user not for opportunity owner, along with email notification like "task has been assigned to you".Once he will complete the task again completion mail should sent to Opportunity Owner and their manager like "Your task has been completd". 
Is this possible to one Trigger for all senarios?  
How we will achieve this senarios.
Please help us for this.

Thanks in Advance
Thota Rakesh 1Thota Rakesh 1
Hi Srini,

The following code is for creating a new task when an opportunity is created.
 
trigger createTask on Opportunity (before insert, before update){ 
List<Task> tasks = new List<Task>(); 
List<Opportunity> Opps = Trigger.new; 
for (Opportunity Opp : Opps) {
Task tsk = new Task(whatID = Opp.ID, Ownerid = Opp.OwnerId); tasks.add(tsk); 
} 
insert tasks; 
}


The below code is for Sending an Email notification.
 
trigger SendEmailToAccount on Contact (after insert) {
    if(Trigger.isAfter){
        if(Trigger.isInsert ){ 
            //helper class for single email but bulk messages
            HelperContactTrigger.sendEmail(trigger.new);
        }
    }
}


Apex Class:

public with sharing class HelperContactTrigger {
    //static method
    public static List<Contact> sendEmail(List<Contact> contacts) {

        //query on template object
        EmailTemplate et=[Select id from EmailTemplate where name=:'Sales: New Customer Email'];

        //list of emails
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

        //loop
        for(Contact con : contacts){

            //check for Account
            if(con.AccountId == null && con.Email != null){

                //initiallize messaging method
                Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();

                //set object Id
                singleMail.setTargetObjectId(con.Id);

                //set template Id
                singleMail.setTemplateId(et.Id);

                //flag to false to stop inserting activity history
                singleMail.setSaveAsActivity(false);

                //add mail
                emails.add(singleMail);

               //This will not send email to contact  
               emails.setTreatTargetObjectAsRecipient(false);
            }
        }



Kindlu mark it as sloved if it helps you.


Best Regards,
Rakesh.T