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
HBF SFDCHBF SFDC 

Trigger to Assign a task automatically to a NON-OWNER user

Hello most excellent Apex development community-

 

I'm looking for an example of how you would go about assigning a task to a related user on a record who is NOT the owner of the record when certain conditions apply.  If anybody could help with this challenge, I would certainly appreciate it!

 

conditions would be

 

Record.Stage is Stage2 AND field X is complete, assign a Task with subject "Please make phone call within 24 hours" to a RELATED USER (Record.Related_User__c).

 

Thanks,

Aaron

SurekaSureka

Hi,

 

You can write the trigger in the corresponding record object:

 

if(Record.Stage == 'Stage2' && Record.x ='Complete')

Task t = new Task();

t.Subject = . 'Please make phone call within 24 hours';

t.AssignedTo = Record.Related_User__c

.........................

.........................

 insert t;

}


Thanks

HBF SFDCHBF SFDC

Thanks for the help, Sureka.

 

I get this error message when I try to save the trigger:

 

ErrorError: Compile Error: Invalid field AssignedTo for SObject Task at line 8 column 1

 

Any idea why? and/or how to fix it?

 

Thanks,

Aaron

Force2b_MikeForce2b_Mike

Aaron,

 

The field name is actually 'OwnerID', even though the label is 'Assigned To'. Can be a bit confusing.

 

Best Regards,

 

Mike

HBF SFDCHBF SFDC

Thanks Mike!

 

I adjusted the line to:

 

t.OwnerID = Complaints__c.Case_Manager__c;

 

and new the error message is:

 

Error: Compile Error: Illegal assignment from Schema.SObjectField to Id at line 8 column 1

 

How do I go about gathering the Related User field's ID to use the ID to assign the proper task owner?

 

Here is the whole bit of code thus far:

 

 

trigger CMCommunciateWithCustomerTask on Complaints__c (before update)

{

if(Complaints__c.Complaint_Status__c == 'Investigation & Root Cause Determination' &&   Complaints__c.Complaint_Category_Responsible_Party__c !=null)

{

Task t = new Task();

t.Subject = 'Please Inform Customer within 24 hours that We are Researching the Problem';

t.OwnerID = Complaints__c.Case_Manager__c;

t.Date = Today()+1;


insert t;

}

}

 

I'd also like to toggle the "Send Email Notification" checkbox to TRUE.  If you have ideas how to do it, that would help tremendously!

 

Thanks,

Aaron

SurekaSureka

Hi,

 

 Does the "Complaints__c.Case_Manager__c" contains UserId?

 

You can assign the Owner id if the feild Case Manager contains a valid user Id. Or if you have the user name query from the user object and assign the Id to t.OwnerId.

 

Hope this helps.

 

Thanks

Force2b_MikeForce2b_Mike

Aaron,

 

Tasks can only be assigned to an active SalesForce.com User. Does Case_Manager__c refer to a Contact or a User? 

 

Also, in Apex there is no "option" for "Send Notification eMail" when creating a task. That is only available when creating a task through the UI. To generate an eMail to the new Task owner through Apex, you have to write code to send the eMail manually. I've included some code I have that does something similar:

 

 

// ----------------------------------------------------------------------
// sendeMail() method
// - Called by the Save() Method to send a Task Assignment eMail
// ----------------------------------------------------------------------
private boolean sendEMail(Task t) {
	string htmlBody = '<HTML><BODY><h3>';
	string textBody = '';

	htmlbody += 'The following Task has just been assigned to you by ' + UserInfo.getName() + '</h3>';
	textBody += 'The following Task has just been assigned to you by ' + UserInfo.getName() + ':\r\r';

	// Use this to get the base URL of the SalesForce instance
	string BaseURL = ApexPages.currentPage().getHeaders().get('Host');
	pageReference tView = new ApexPages.StandardController(t).view();
	htmlBody += '<ul><li>Task: <a href="' + BaseURL + tView.getUrl() + '">' + t.Subject + '</a>';
	htmlBody += '<li>Due Date: ' + t.ActivityDate;
	htmlBody += '<li>Priority: ' + t.Priority;
	htmlBody += '</ul></body></html>';

	textBody += '\t\tSubject: ' + t.subject;
	textBody += '\tTask Link: ' + BaseURL + tView.getUrl();
	textBody += '\tDue Date: ' + t.ActivityDate;
	textBody += '\tPriority: ' + t.Priority;

	// Get the target user eMail address
	User user = [SELECT ID, eMail FROM User Where ID = :t.ownerId Limit 1];

	// Create the eMail object
	Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

	// Set the TO address
	String[] toAddresses = new String[] {user.Email};
	mail.setToAddresses(toAddresses);

	// Specify the name used as the display name.
	mail.setSenderDisplayName(UserInfo.getName());

	// Specify the subject line for your email address.
	mail.setSubject('SalesForce.com Task Assigned: ' + t.subject);

	// Set options
	mail.setBccSender(false);
	mail.setUseSignature(false);

	// Specify the text content of the email.
	mail.setPlainTextBody(textBody);
	mail.setHtmlBody(htmlBody);

	// Send the email
	Messaging.SendEmailResult [] sr = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

	if (!sr[0].isSuccess()) {
		// Error sending the message; display the error on the page
		Messaging.SendEmailError r = sr[0].getErrors()[0];
		ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error Sending Message: ' + sr[0].getErrors()[0].getMessage() ));
		return false;
	} else { return true; }

}

 

 

 

Best Regards,

 

Mike

testytesttestytest

Sorry, I'm a newbie to this.  But I would also like to be able to assign a task to a related user for a custom object.  

 

The custom object is "Company__Tests__c"

A user will be assigned "Company__Assigned_To__c"

I have a status field "Company__Status__c"  defaulted to "Not Started" whenever a record is created.

 

So how would I code this trigger for a task to the related user, for whenever this record is created ?  I tried to use the reference above but I kept getting the token error message.  

 

TIA

babrannobabranno

I am new to apex and I am trying to use this but I am having trouble.  I put your code into a public class called sendEMail and was able to save the class.  However when I try calling the class from the trigger it is telling me that the method does not exisit.  Can you provide any insight on how to get this to work.  I have included my trigger below.  Any help would be appreciated.

 

trigger UWTask on Applications__c (after insert,after update) {


//Insert Trigger

If(trigger.isinsert){

sendEMail s = new sendEMail();
Task[] t = new Task[0];
for(Applications__c app:trigger.new)
{if(app.Application_Underwriter__c != null &&
app.UW_Committed_Deal__c == True && app.Committed_Deal__c == False &&app.RecordTypeid == '012E0000000PPsTIAW')
{t.add
(new task
(subject = 'UW App Follow-up',
ownerid = app.Application_Underwriter__c,
activitydate = system.today().adddays(1),
whatid = app.id,
recordtypeid = '012E0000000PQRaIAO'));
}
}
insert t;
s.sendEMail;

}

If(trigger.isinsert){

Task[] tasks = new Task[0];
for(Applications__c app:trigger.new)
{if(app.Application_Underwriter__c != null &&
app.UW_Committed_Deal__c == False && app.Committed_Deal__c == True &&app.RecordTypeid == '012E0000000PPsTIAW')
{tasks.add
(new task
(subject = 'UW App Follow-up',
ownerid = app.Application_Underwriter__c,
activitydate = system.today().adddays(1),
whatid = app.id,
recordtypeid = '012E0000000PQRaIAO'));
}
}
insert tasks;
}

//Update Trigger

If(trigger.isupdate){

Task[] tasks = new Task[0];
for(Applications__c app:trigger.new)
{if(trigger.oldMap.get(app.id).UW_Committed_Deal__c == False &&
app.UW_Committed_Deal__c == True &&
app.Committed_Deal__c == False &&
app.RecordTypeid == '012E0000000PPsTIAW')
{tasks.add
(new task
(subject = 'UW App Follow-up',
ownerid = app.Application_Underwriter__c,
activitydate = system.today().adddays(1),
whatid = app.id,
recordtypeid = '012E0000000PQRaIAO'));
}
}
insert tasks;

}

If(trigger.isupdate){

Task[] tasks = new Task[0];
for(Applications__c app:trigger.new)
{if(trigger.oldMap.get(app.id).Committed_Deal__c == False &&
app.UW_Committed_Deal__c == False &&
app.Committed_Deal__c == True &&
app.RecordTypeid == '012E0000000PPsTIAW')
{tasks.add
(new task
(subject = 'UW App Follow-up',
ownerid = app.Application_Underwriter__c,
activitydate = system.today().adddays(1),
whatid = app.id,
recordtypeid = '012E0000000PQRaIAO'));
}
}
insert tasks;

}

}

Deepika G PDeepika G P
Hi all,

Below trigger is working fine as per the requirement but when i run the test class , below error is thrown ,
Can anyone help me on this please?
UpdateProjectScheduleFieldsTriggererrorMsgSystem.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, updatetaskoriginfield: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.updatetaskoriginfield: line 15, column 1: [] 
Stack Trace: Class.UpdateProjectScheduleFieldsTrigger.errorMsg: line 14, column 1



trigger updatetaskoriginfield on Task (before insert, before update)
 {
     if(trigger.isBefore)
     {
       
       // please add your object Name here for Customer_participation__c

       String keyPrefix = Customer_participation__c.sObjectType.getDescribe().getKeyPrefix();

     //  System.debug('PREFIX--' + keyPrefix );
           for(Task tsk: trigger.new )
            {
             String strWhatId = tsk.whatId;
             //  if(strWhatId.startsWith('a0v'))   
                if( strWhatId.startsWith(keyPrefix) ) // Chck record is related with Customer_participation__c only
                {
                 String test=tsk.subject;
                 set<string> a=new Set<string>{'executive','Executive'};
                 set<string> b=new Set<string>{'award','Award'};
                 List<String> lsttest=test.split(' ');
                 for(String s: lsttest)
                 {
                     if(a.contains(s))
                     {
                           tsk.Task_Origin__c='Executive Summary';
                     }
                     else if(b.contains(s))
                     {
                           tsk.Task_Origin__c='Award Notification';
                     }
                }
             }  
     }  
     }   
}