• Lucifer
  • NEWBIE
  • 0 Points
  • Member since 2012

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 15
    Questions
  • 21
    Replies

Hi,

 

I have this trigger in my sandbox and during a training session for new employees, I got this error.

 

caused by: System.NullPointerException: Attempt to de-reference a null object

 Trigger.ValidateCase: line 18, column 1

 

This is my trigger. I colored the error line which is line 18

 

 

/*Validations:
1. Case should be closed when case has some open taks.
*/

trigger ValidateCase on Case (before Update) {
if(Trigger.isBefore && Trigger.isUpdate)
{
Map<Id,List<Task>> CaseIdtoTasksnotclosedMap = new Map<Id,List<Task>>();
List<Task> tasks;
for(Task t : [Select Id,status,whatId,Subject from Task where whatId IN :Trigger.NewMap.keyset()])//Collect all open tasks with single query.
{
tasks = CaseIdtoTasksnotclosedMap.keyset().contains(t.whatId) ? CaseIdtoTasksnotclosedMap.get(t.whatId) : new List<task>();
if(!t.status.equalsIgnorecase('Completed')) tasks.add(t);
CaseIdtoTasksnotclosedMap.put(t.whatId,tasks);
}
for(Case c : Trigger.new)
{
if(c.status != Trigger.oldmap.get(c.Id).status && c.status.equalsIgnorecase('closed') && CaseIdtoTasksnotclosedMap.get(c.Id).size() > 0)
{
String taskNames = '';
for(task t : CaseIdtoTasksnotclosedMap.get(c.Id)) taskNames += t.Subject+' '; //collect all open task names.
c.addError('you Cannot close when case has some open tasks. {'+ taskNames +'}');//add error message to case record.
c.status.addError('Case has some open tasks');//add error message to case status field.
}
}
}

}



  • September 16, 2013
  • Like
  • 0
I use an ETL tool that dumps all cases, contacts, users in salesforce to a sql database. Presently what im doing is I have the job saved in my ETL tool with the query Select * from cases and every time I run the job I set the condition to delete the existing table and create new table so there wont be duplicates whenever I run the job. Now I was asked to create a job that runs every night. So I dont want to use the query select * from cases as it would take atleast 5 hours to complete the job.
 
So I was looking for a customised query which should be this way.
 
select * from cases where created or updated time >= last dump date
 
 
So that way my job just fetches the updated and the newly created cases every day sparing the rest. 
 
 
Can I get it in some salesforce proper SOQL syntax please... That way I can query it in the ETL tool instead of using select * from cases every time I try to dump..
  • September 03, 2013
  • Like
  • 0

trigger CalculateWaitTimeInHours on Case (before insert, before update) {
    if (Trigger.isInsert) {
        for (Case updatedCase:System.Trigger.new) {
            updatedCase.Last_Status_Change__c = System.now();
            updatedCase.Hours_In_Wait_Status__c = 0;
            updatedCase.Hours_Not_In_Wait_Status__c = 0;
        }
    } else {

        // get the wait statuses configured on system
        Set<String> waitStatusSet = new Set<String>();
        for (Wait_Status__c waitStatus:[Select Name From Wait_Status__c]) {
            waitStatusSet.add(waitStatus.Name);
        }

        // get the default business hours
        BusinessHours defaultHours = [select Id from BusinessHours where IsDefault=true];

        // get the closed statuses (because at the point of this trigger Case.IsClosed won't be set yet)
        Set<String> closedStatusSet = new Set<String>();
        for (CaseStatus status:[Select MasterLabel From CaseStatus where IsClosed=true]) {
            closedStatusSet.add(status.MasterLabel);
        }

        // for any case where the status is changed, recalc the business hours in the buckets
        for (Case updatedCase:System.Trigger.new) {
            Case oldCase = System.Trigger.oldMap.get(updatedCase.Id);

            if (oldCase.Status!=updatedCase.Status && updatedCase.Last_Status_Change__c!=null) {
                //OK, the status has changed
                if (!oldCase.IsClosed) {
                    //We only update the buckets for open cases

                    //On the off-chance that the business hours on the case are null, use the default ones instead
                    Id hoursToUse = updatedCase.BusinessHoursId!=null?updatedCase.BusinessHoursId:defaultHours.Id;

                    //The diff method comes back in milliseconds, so we divide by 3600000 to get hours.
                    Double timeSinceLastStatus = BusinessHours.diff(hoursToUse, updatedCase.Last_Status_Change__c, System.now())/3600000.0;
                    System.debug(timeSinceLastStatus);

                    //We decide which bucket to add it to based on whether it was in a stop status before
                    if (waitStatusSet.contains(oldCase.Status)) {
                        updatedCase.Hours_In_Wait_Status__c += timeSinceLastStatus;
                    } else {
                        updatedCase.Hours_Not_In_Wait_Status__c += timeSinceLastStatus;
                    }

                    System.debug(updatedCase.Status);
                    if (closedStatusSet.contains(updatedCase.Status)) {
                        System.debug(updatedCase.Hours_In_Wait_Status__c);
                        System.debug(updatedCase.Hours_Not_In_Wait_Status__c);
                        updatedCase.Case_Age_In_Business_Hours__c = updatedCase.Hours_In_Wait_Status__c + updatedCase.Hours_Not_In_Wait_Status__c;
                    }
                }

                updatedCase.Last_Status_Change__c = System.now();
            }
        }
    }
}

Hi there,

 

I am asked to create a report to see how long an owner owned a case. For eg Case is created by me and owned it for 5 hours, then assigned it to A for 3 hours and finally assigned it to B and he closed it after 3 hours. So I need a report about all these users and their time. Just like case history, I created a case child object called Caseowners but I know it involves apex coding to do this. Can some one help me on this or give me a sample code?

 

Thanks.

Hi all,

 

I have to calculate the total time spent on a case. We have 5 status called new open pending working closed. So when ever the status is in working then the time is not supposed to be calculated. For this I have written a trigger which subtratcs the waiting time from total time. But looks like I had a problm. 

 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger caselifetimecalculator caused an unexpected exception, contact your administrator: caselifetimecalculator: execution of BeforeUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.caselifetimecalculator: line 6, column 1

 

 

Her is my code

 

trigger caselifetimecalculator on Case (before update) {
 
  for(Case c:Trigger.New){ 
   if(Trigger.oldMap.get(c.id).status != c.status)
       if(Trigger.oldMap.get(c.id).status !='Waiting' )
           c.total_activity_time__c +=  (datetime.now().getTime()- (c.CaseStatusLastModified__c == null ? c.CreatedDate.getTime() :c.CaseStatusLastModified__c.getTime()))/(1000*60);
       c.CaseStatusLastModified__c= datetime.now();
  }
 
}
 
 
 
Please create two fields on Case and expose"Total Activity Time" on layout.
 
 
 
     label                           type                     api                                           Help text
1.. "Total Activity time"    Number (10,5)  total_activity_time                        In seconds.       
2. "casestatuslastmodified" Date/time     CaseStatusLastModified

 

 

Hi All,

 

I have an object in which every record created 9 tasks. The owner of the task is not the the record owner but its a project manager which is a custom field in the Object. I wrote a trigger which would create tasks in such a way and will send email to the project manager.  So I wrote  a scheduling job which is supposed to run every night and send reminder emails to respected project manager of the record 2 days before over due. I'm not sure where its going wrong but I don't get the result. Can some one help me please?

 

 

global class EscalateAnnualEnrollmentTaskProcess implements Schedulable {
global void execute(SchedulableContext ctx)
{

System.debug('Starting');

DateTime Dt = System.Now();
Date D = Date.newInstance(Dt.year(),Dt.Month(),Dt.day());


system.debug('*********************************DT'+Dt);
system.debug('*********************************D'+D);

/* list of open annual enrollment requests */
List<Annual_Enrollment_Request__c> requestIds = new List<Annual_Enrollment_Request__c>();
requestIds = [SELECT Id FROM Annual_Enrollment_Request__c WHERE status__c != 'ACCEPT'];

system.debug('*********************************reqiestIds'+requestIds);
/* list of tasks associated with these requests near overdue activitydate - 2 */
List<Task> tasksOverdue = new List<Task>();
if(requestIds.size()>0 & requestIds.size()<>null){
tasksOverdue =[SELECT Id, WhatId, ActivityDate, Subject FROM Task WHERE WhatId IN :requestIds AND IsClosed = false AND ActivityDate <= :D.addDays(+2) ] ;
}
system.debug('*********************************D.addDays(-2)'+D.addDays(-2));
system.debug('*********************************taskOverdue'+tasksOverdue);


if(tasksOverdue.size()>0 & tasksOverdue.size()<>null){
for (Task t:tasksOverdue) {
/* lookup the object */
list <Annual_Enrollment_Request__c> req = new list <Annual_Enrollment_Request__c>();

req= [SELECT Id, Project_Manager__c, Director__c FROM Annual_Enrollment_Request__c WHERE Id = :t.WhatId ];
if(req.size() > 0){
for(Annual_Enrollment_Request__c request: req){
System.debug('Vamsi.t.projectmanager : ' + request.Project_Manager__c);
/* lookup the user and send the email*/
list<User> pm = new list<User>();
pm = [SELECT Id, Name, Email FROM User WHERE Id = :request.Project_Manager__c LIMIT 1];
if(pm.size()>0){
for(User projectmanager :pm){
sendemail(projectmanager, t);
}
}
/* lookup the user and send the email */
list<User> dir = new list<User>();
dir = [SELECT Id, Name, Email FROM User WHERE Id = :request.Director__c LIMIT 1];
if(dir.size() >0){
for(User director : dir){
System.debug('Vamsi.t.director : ' + director);
sendemail(director, t);
}
}
}
}
}
}

}
global void sendemail(User projectmanager, Task t)
{
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
string[] toaddress = New String[] {projectmanager.Email};
email.setSubject('Task Almost Overdue');
email.setPlainTextBody(t.Subject + 'is due ' + t.ActivityDate + ' and needs some attention.');
email.setToAddresses(toaddress);
Messaging.sendEmail(New Messaging.SingleEmailMessage[] {email});
}
}

I have an issue with the email template. I wanted to put the record name(Auto number field) in to the tepmlate. This is an email triggering on task. SO I'm able to get the task fields but wanted to get the name of the record on which the task is creating.

 

 

Essentially im looking for an output in this fashion:      

Task Name = ARQ 000001   Hello Lucifer  a subject Pre-Meeting1 with Priority Not Started and duedate 2012-11-27 00:00:00 is been created.Please click here to open task

 

 

mail.setHTMLBody    ('Task Name = ' +tsk.related.Annual_Request__r.Name +'Hello  ' +theUser.Name+' '+ 'a subject '+tsk.Subject+' '+'with Priority '+tsk.status +' '+ 'and duedate ' + tsk.Activitydate +' '+'is been created.'+'<a href="https://cs3.salesforce.com/'+tsk.Id+'">Please click here to open task<a/>');

 

 

Please help me with this..

Hey all,

 

I wrote a trigger which would create a task assigned to a particular field in a record. But I wanted to also send an email notification which I couldn't do like how I did the task.priority, task.subject etc..

 

Below is my code 

 

 

rigger createTask On Annual_Enrollment_Request__c (after insert)
{

List <task> taskToInsert = new List <task> ();

for (Annual_Enrollment_Request__c Are : Trigger.new) {

 

Task task = new Task ();

task.ActivityDate = Are.Date1__c; // and so on so forth untill you map all the fields.
task.Subject = 'Pre-Meeting';
task.OwnerId = Are.Project_Manager__c;
//task.WhoId = Are.Project_Manager__c ;
task.whatId = Are.id;
task.status = 'Not Started';
task.priority = 'Normal';
task.Description = ' Meeting ahead. Got to discuss things!!';


System.debug('***********'+task);
taskToInsert.add(task);

 

//once loop is done, you need to insert new records in SF
// dml operations might cause an error, so you need to catch it with try/catch block.
try {
insert taskToInsert;
} catch (system.Dmlexception e) {
system.debug (e);
}

}

 

 

I found out that apex do not support this way and we need to code it again? If so how? Do I need to include here in the same trigger or write an other trigger? 

Hi all,

 

I have a workflow which creates two tasks when ever a record is created. To create a record I have 4 fields.

1)Year

2)Status

3)Project Manager

4)DIrector.

 

Now my question is when ever I create a record, My tasks which would be created should be assigned to the project manager dynamically. 

 

So we are looking at some 100 records where say may be 10 diffrent project managers are owning each 10 records.

 

So example 

 

If the project manager field is filled with the name Thomas then the work flow should trigger creating two tasks assigning them to thomas.

 

Similarly for Robin, kayla etc.

 

So I would insert 100 records with a dataloader and all records should be created with two tasks each assigned to respective PM .

 

If the task is always assigned to a single person, I'm able to do that but dynamically changing is what im faceing trouble.

 

Could some one help me in this. Can it be performed using wokflows or it needs to be coded?

I have a situation when ever I insert a record a work flow fires and creates two tasks. What my question is... If I'm asked to insert those records using a data loader will workflow also fires then?  Cos right now for testing purpose I am manually entering the fields in the record and saving.. Just wanted to know if it works for bulk uploads. I tried doing one record using dataloader and it fired. But Just wanted to confirm that with 100 records

Hey Guys, 

I have been working on it from past 2 days but couldn't crack it. I'm writing a schedule job which runs every night and at 2 days before a taskoverdue it should send email to the assignees alerting them of the situation. The code I have wriyyen is missing a slight logic and I'm not getting the result. Could some one look at it pls.. I doubt the redline..

 

 

global class EscalateAnnualEnrollmentTaskProcess implements Schedulable {
global void execute(SchedulableContext ctx)
{
/* list of open annual enrollment requests */
List<Annual_Enrollment_Request__c> requestIds = [SELECT Id FROM Annual_Enrollment_Request__c WHERE status__c != 'ACCEPTED'];
/* list of tasks associated with these requests near overdue activitydate - 2 */
List<Task> tasksNearOverdue =[SELECT Id, ActivityDate, Subject FROM Task WHERE WhatId IN :requestIds AND IsClosed = false AND ActivityDate <= :Date.today().addDays(-2) ] ;
/* iterate over the tasks */
for (Task t:tasksNearOverdue) {
/* lookup the object */
Annual_Enrollment_Request__c request = [SELECT Id, Project_Manager__c, Director__c FROM Annual_Enrollment_Request__c WHERE Id = :t.WhatId];

/* lookup the user and send the email*/
User projectmanager = [SELECT Id, Name, Email FROM User WHERE Id = :request.Project_Manager__c];
sendemail(projectmanager, t);
/* lookup the user and send the email */
User director = [SELECT Id, Name, Email FROM User WHERE Id = :request.Director__c];
sendemail(director, t);
}

}
global void sendemail(User u, Task t)
{
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
string[] toaddress = New String[] {u.Email};
email.setSubject('Task Almost Overdue');
email.setPlainTextBody(t.Subject + 'is due ' + t.ActivityDate + ' and needs some attention.');
email.setToAddresses(toaddress);
Messaging.sendEmail(New Messaging.SingleEmailMessage[] {email});
}
}

I'm trying to create a shedule job that sends email alerts 2 days befor due date. But some how list task near overdue doesn't let me save. It shows problem with the last "And" part( The highlighted part). Could somebody point me out where I am going wrong?  

 

 


List<Task> tasksNearOverdue =[SELECT Id, ActivityDate, Subject FROM Task WHERE WhatId IN :requestIds AND IsClosed = false AND :Date.today().addDays(-2) >= ActivityDate ] ;

Hi All,

 

I have a schedule job of email alerts for task due date. It runs every day at 7.00am and checks for task over dues. If I created a record at 1.00pm with the overdue coondition satisfying then do I get a mail instantaneously or I get mail when the scheduled job run tomorrow at 7.00 and sees this as overdue and maile me?

Im trying to run a batch apex for my code

 

/************************************************************************/

EscalateAnnualEnrollmentTaskProcess AE = new EscalateAnnualEnrollmentTaskProcess();
database.executebatch(AE);


/************************************************************************/


global class TaskProcess implements Schedulable {
   global void execute(SchedulableContext ctx) 
   {
      /*  */
      List<Request__c> requestIds = [SELECT Id FROM Request__c WHERE status__c != 'ACCEPTED'];
      /* list of tasks associated near overdue activitydate - 5*/
      List<Task>Overdue =new List<Task>([SELECT Id, ActivityDate, Subject FROM Task WHERE WhatId IN :requestIds AND IsClosed = false]);
      /* iterate over the tasks */
      for (Task t:tasksNearOverdue) {
         /* lookup the object */
         Request__c request = [SELECT Id, Project_Manager__c, Director__c FROM Request__c WHERE Id = :t.WhatId];
 

         /* lookup the user and send the email*/
         User manager = [SELECT Id, Name, Email FROM User WHERE Id = :request.Project_Manager__c];
         sendemail(projectmanager, t);
         /* lookup the user and send the email */
         User director =  [SELECT Id, Name, Email FROM User WHERE Id = :request.Director__c];
         sendemail(director, t);
      }
   
 } 
   global void sendemail(User u, Task t)
   {
      Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
      string[] toaddress = New String[] {u.Email};
      email.setSubject('Task Almost Overdue');
      email.setPlainTextBody(t.Subject + 'is due ' + t.ActivityDate + ' and needs some attention.');
      email.setToAddresses(toaddress);
      Messaging.sendEmail(New Messaging.SingleEmailMessage[] {email});
   }
}

Hi.. Im trying to implement a scheduling job email alert for a task which is over due.. I'm getting this following error..  

 

 Method does not exist or incorrect signature: [Messaging.SingleEmailMessage].setToAddress(LIST<String>) at line 29 column 7

 

 



global void sendemail(User u, Task t)
{
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
string[] toaddress = New String[] {u.Email};
email.setSubject('Task Almost Overdue');
email.setPlainTextBody(t.Subject + 'is due ' + t.ActivityDate + ' and needs some attention.');
email.setToAddress(toaddress);
Messaging.sendEmail(New Messaging.SingleEmailMessage[] {email});
}
}

Hi,

 

I have this trigger in my sandbox and during a training session for new employees, I got this error.

 

caused by: System.NullPointerException: Attempt to de-reference a null object

 Trigger.ValidateCase: line 18, column 1

 

This is my trigger. I colored the error line which is line 18

 

 

/*Validations:
1. Case should be closed when case has some open taks.
*/

trigger ValidateCase on Case (before Update) {
if(Trigger.isBefore && Trigger.isUpdate)
{
Map<Id,List<Task>> CaseIdtoTasksnotclosedMap = new Map<Id,List<Task>>();
List<Task> tasks;
for(Task t : [Select Id,status,whatId,Subject from Task where whatId IN :Trigger.NewMap.keyset()])//Collect all open tasks with single query.
{
tasks = CaseIdtoTasksnotclosedMap.keyset().contains(t.whatId) ? CaseIdtoTasksnotclosedMap.get(t.whatId) : new List<task>();
if(!t.status.equalsIgnorecase('Completed')) tasks.add(t);
CaseIdtoTasksnotclosedMap.put(t.whatId,tasks);
}
for(Case c : Trigger.new)
{
if(c.status != Trigger.oldmap.get(c.Id).status && c.status.equalsIgnorecase('closed') && CaseIdtoTasksnotclosedMap.get(c.Id).size() > 0)
{
String taskNames = '';
for(task t : CaseIdtoTasksnotclosedMap.get(c.Id)) taskNames += t.Subject+' '; //collect all open task names.
c.addError('you Cannot close when case has some open tasks. {'+ taskNames +'}');//add error message to case record.
c.status.addError('Case has some open tasks');//add error message to case status field.
}
}
}

}



  • September 16, 2013
  • Like
  • 0
I use an ETL tool that dumps all cases, contacts, users in salesforce to a sql database. Presently what im doing is I have the job saved in my ETL tool with the query Select * from cases and every time I run the job I set the condition to delete the existing table and create new table so there wont be duplicates whenever I run the job. Now I was asked to create a job that runs every night. So I dont want to use the query select * from cases as it would take atleast 5 hours to complete the job.
 
So I was looking for a customised query which should be this way.
 
select * from cases where created or updated time >= last dump date
 
 
So that way my job just fetches the updated and the newly created cases every day sparing the rest. 
 
 
Can I get it in some salesforce proper SOQL syntax please... That way I can query it in the ETL tool instead of using select * from cases every time I try to dump..
  • September 03, 2013
  • Like
  • 0

Hi there,

 

I am asked to create a report to see how long an owner owned a case. For eg Case is created by me and owned it for 5 hours, then assigned it to A for 3 hours and finally assigned it to B and he closed it after 3 hours. So I need a report about all these users and their time. Just like case history, I created a case child object called Caseowners but I know it involves apex coding to do this. Can some one help me on this or give me a sample code?

 

Thanks.

Hi all,

 

I have to calculate the total time spent on a case. We have 5 status called new open pending working closed. So when ever the status is in working then the time is not supposed to be calculated. For this I have written a trigger which subtratcs the waiting time from total time. But looks like I had a problm. 

 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger caselifetimecalculator caused an unexpected exception, contact your administrator: caselifetimecalculator: execution of BeforeUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.caselifetimecalculator: line 6, column 1

 

 

Her is my code

 

trigger caselifetimecalculator on Case (before update) {
 
  for(Case c:Trigger.New){ 
   if(Trigger.oldMap.get(c.id).status != c.status)
       if(Trigger.oldMap.get(c.id).status !='Waiting' )
           c.total_activity_time__c +=  (datetime.now().getTime()- (c.CaseStatusLastModified__c == null ? c.CreatedDate.getTime() :c.CaseStatusLastModified__c.getTime()))/(1000*60);
       c.CaseStatusLastModified__c= datetime.now();
  }
 
}
 
 
 
Please create two fields on Case and expose"Total Activity Time" on layout.
 
 
 
     label                           type                     api                                           Help text
1.. "Total Activity time"    Number (10,5)  total_activity_time                        In seconds.       
2. "casestatuslastmodified" Date/time     CaseStatusLastModified

 

 

Hi All,

 

I have an object in which every record created 9 tasks. The owner of the task is not the the record owner but its a project manager which is a custom field in the Object. I wrote a trigger which would create tasks in such a way and will send email to the project manager.  So I wrote  a scheduling job which is supposed to run every night and send reminder emails to respected project manager of the record 2 days before over due. I'm not sure where its going wrong but I don't get the result. Can some one help me please?

 

 

global class EscalateAnnualEnrollmentTaskProcess implements Schedulable {
global void execute(SchedulableContext ctx)
{

System.debug('Starting');

DateTime Dt = System.Now();
Date D = Date.newInstance(Dt.year(),Dt.Month(),Dt.day());


system.debug('*********************************DT'+Dt);
system.debug('*********************************D'+D);

/* list of open annual enrollment requests */
List<Annual_Enrollment_Request__c> requestIds = new List<Annual_Enrollment_Request__c>();
requestIds = [SELECT Id FROM Annual_Enrollment_Request__c WHERE status__c != 'ACCEPT'];

system.debug('*********************************reqiestIds'+requestIds);
/* list of tasks associated with these requests near overdue activitydate - 2 */
List<Task> tasksOverdue = new List<Task>();
if(requestIds.size()>0 & requestIds.size()<>null){
tasksOverdue =[SELECT Id, WhatId, ActivityDate, Subject FROM Task WHERE WhatId IN :requestIds AND IsClosed = false AND ActivityDate <= :D.addDays(+2) ] ;
}
system.debug('*********************************D.addDays(-2)'+D.addDays(-2));
system.debug('*********************************taskOverdue'+tasksOverdue);


if(tasksOverdue.size()>0 & tasksOverdue.size()<>null){
for (Task t:tasksOverdue) {
/* lookup the object */
list <Annual_Enrollment_Request__c> req = new list <Annual_Enrollment_Request__c>();

req= [SELECT Id, Project_Manager__c, Director__c FROM Annual_Enrollment_Request__c WHERE Id = :t.WhatId ];
if(req.size() > 0){
for(Annual_Enrollment_Request__c request: req){
System.debug('Vamsi.t.projectmanager : ' + request.Project_Manager__c);
/* lookup the user and send the email*/
list<User> pm = new list<User>();
pm = [SELECT Id, Name, Email FROM User WHERE Id = :request.Project_Manager__c LIMIT 1];
if(pm.size()>0){
for(User projectmanager :pm){
sendemail(projectmanager, t);
}
}
/* lookup the user and send the email */
list<User> dir = new list<User>();
dir = [SELECT Id, Name, Email FROM User WHERE Id = :request.Director__c LIMIT 1];
if(dir.size() >0){
for(User director : dir){
System.debug('Vamsi.t.director : ' + director);
sendemail(director, t);
}
}
}
}
}
}

}
global void sendemail(User projectmanager, Task t)
{
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
string[] toaddress = New String[] {projectmanager.Email};
email.setSubject('Task Almost Overdue');
email.setPlainTextBody(t.Subject + 'is due ' + t.ActivityDate + ' and needs some attention.');
email.setToAddresses(toaddress);
Messaging.sendEmail(New Messaging.SingleEmailMessage[] {email});
}
}

Can we have a custom email for tasks through triggers. 

 

Any code snipet will be very helpful

Hey all,

 

I wrote a trigger which would create a task assigned to a particular field in a record. But I wanted to also send an email notification which I couldn't do like how I did the task.priority, task.subject etc..

 

Below is my code 

 

 

rigger createTask On Annual_Enrollment_Request__c (after insert)
{

List <task> taskToInsert = new List <task> ();

for (Annual_Enrollment_Request__c Are : Trigger.new) {

 

Task task = new Task ();

task.ActivityDate = Are.Date1__c; // and so on so forth untill you map all the fields.
task.Subject = 'Pre-Meeting';
task.OwnerId = Are.Project_Manager__c;
//task.WhoId = Are.Project_Manager__c ;
task.whatId = Are.id;
task.status = 'Not Started';
task.priority = 'Normal';
task.Description = ' Meeting ahead. Got to discuss things!!';


System.debug('***********'+task);
taskToInsert.add(task);

 

//once loop is done, you need to insert new records in SF
// dml operations might cause an error, so you need to catch it with try/catch block.
try {
insert taskToInsert;
} catch (system.Dmlexception e) {
system.debug (e);
}

}

 

 

I found out that apex do not support this way and we need to code it again? If so how? Do I need to include here in the same trigger or write an other trigger? 

Hi all,

 

I have a workflow which creates two tasks when ever a record is created. To create a record I have 4 fields.

1)Year

2)Status

3)Project Manager

4)DIrector.

 

Now my question is when ever I create a record, My tasks which would be created should be assigned to the project manager dynamically. 

 

So we are looking at some 100 records where say may be 10 diffrent project managers are owning each 10 records.

 

So example 

 

If the project manager field is filled with the name Thomas then the work flow should trigger creating two tasks assigning them to thomas.

 

Similarly for Robin, kayla etc.

 

So I would insert 100 records with a dataloader and all records should be created with two tasks each assigned to respective PM .

 

If the task is always assigned to a single person, I'm able to do that but dynamically changing is what im faceing trouble.

 

Could some one help me in this. Can it be performed using wokflows or it needs to be coded?

I have a situation when ever I insert a record a work flow fires and creates two tasks. What my question is... If I'm asked to insert those records using a data loader will workflow also fires then?  Cos right now for testing purpose I am manually entering the fields in the record and saving.. Just wanted to know if it works for bulk uploads. I tried doing one record using dataloader and it fired. But Just wanted to confirm that with 100 records

Hey Guys, 

I have been working on it from past 2 days but couldn't crack it. I'm writing a schedule job which runs every night and at 2 days before a taskoverdue it should send email to the assignees alerting them of the situation. The code I have wriyyen is missing a slight logic and I'm not getting the result. Could some one look at it pls.. I doubt the redline..

 

 

global class EscalateAnnualEnrollmentTaskProcess implements Schedulable {
global void execute(SchedulableContext ctx)
{
/* list of open annual enrollment requests */
List<Annual_Enrollment_Request__c> requestIds = [SELECT Id FROM Annual_Enrollment_Request__c WHERE status__c != 'ACCEPTED'];
/* list of tasks associated with these requests near overdue activitydate - 2 */
List<Task> tasksNearOverdue =[SELECT Id, ActivityDate, Subject FROM Task WHERE WhatId IN :requestIds AND IsClosed = false AND ActivityDate <= :Date.today().addDays(-2) ] ;
/* iterate over the tasks */
for (Task t:tasksNearOverdue) {
/* lookup the object */
Annual_Enrollment_Request__c request = [SELECT Id, Project_Manager__c, Director__c FROM Annual_Enrollment_Request__c WHERE Id = :t.WhatId];

/* lookup the user and send the email*/
User projectmanager = [SELECT Id, Name, Email FROM User WHERE Id = :request.Project_Manager__c];
sendemail(projectmanager, t);
/* lookup the user and send the email */
User director = [SELECT Id, Name, Email FROM User WHERE Id = :request.Director__c];
sendemail(director, t);
}

}
global void sendemail(User u, Task t)
{
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
string[] toaddress = New String[] {u.Email};
email.setSubject('Task Almost Overdue');
email.setPlainTextBody(t.Subject + 'is due ' + t.ActivityDate + ' and needs some attention.');
email.setToAddresses(toaddress);
Messaging.sendEmail(New Messaging.SingleEmailMessage[] {email});
}
}

I'm trying to create a shedule job that sends email alerts 2 days befor due date. But some how list task near overdue doesn't let me save. It shows problem with the last "And" part( The highlighted part). Could somebody point me out where I am going wrong?  

 

 


List<Task> tasksNearOverdue =[SELECT Id, ActivityDate, Subject FROM Task WHERE WhatId IN :requestIds AND IsClosed = false AND :Date.today().addDays(-2) >= ActivityDate ] ;

Hi All,

 

I have a schedule job of email alerts for task due date. It runs every day at 7.00am and checks for task over dues. If I created a record at 1.00pm with the overdue coondition satisfying then do I get a mail instantaneously or I get mail when the scheduled job run tomorrow at 7.00 and sees this as overdue and maile me?

Im trying to run a batch apex for my code

 

/************************************************************************/

EscalateAnnualEnrollmentTaskProcess AE = new EscalateAnnualEnrollmentTaskProcess();
database.executebatch(AE);


/************************************************************************/


global class TaskProcess implements Schedulable {
   global void execute(SchedulableContext ctx) 
   {
      /*  */
      List<Request__c> requestIds = [SELECT Id FROM Request__c WHERE status__c != 'ACCEPTED'];
      /* list of tasks associated near overdue activitydate - 5*/
      List<Task>Overdue =new List<Task>([SELECT Id, ActivityDate, Subject FROM Task WHERE WhatId IN :requestIds AND IsClosed = false]);
      /* iterate over the tasks */
      for (Task t:tasksNearOverdue) {
         /* lookup the object */
         Request__c request = [SELECT Id, Project_Manager__c, Director__c FROM Request__c WHERE Id = :t.WhatId];
 

         /* lookup the user and send the email*/
         User manager = [SELECT Id, Name, Email FROM User WHERE Id = :request.Project_Manager__c];
         sendemail(projectmanager, t);
         /* lookup the user and send the email */
         User director =  [SELECT Id, Name, Email FROM User WHERE Id = :request.Director__c];
         sendemail(director, t);
      }
   
 } 
   global void sendemail(User u, Task t)
   {
      Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
      string[] toaddress = New String[] {u.Email};
      email.setSubject('Task Almost Overdue');
      email.setPlainTextBody(t.Subject + 'is due ' + t.ActivityDate + ' and needs some attention.');
      email.setToAddresses(toaddress);
      Messaging.sendEmail(New Messaging.SingleEmailMessage[] {email});
   }
}