+ Start a Discussion
babrannobabranno 

Apex Trigger to Create Task for Non-Owner

I am trying to create a task for someone listed on a custom object called Applications__c.  The user on the custom object is a lookup field to the User object.  Below is my query.  I have tried this several different ways all shown below, but each time I get an error when I try to save.  I have put the error below.  Any help would be appreciated.

 

 

Error

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

 

Trigger Version 1

 

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

 

ID s = Applications__c.Application_Underwriter__r.Id;
User uw = [Select Id from User Where Id = :s];


if(Applications__c.UW_Committed_Deal__c == 'True' && Applications__c.UW_Committed_Deal__c == 'False')
{Task t = new task();
t.Subject = 'UW App Follow-up';
t.OwnerID = uw;
t.ActivityDate = Date.today() + 1;
t.WhatId = Applications__c.ID;
t.RecordTypeId = '012E0000000PQRaIAO';
insert t;
}

}

 

Trigger Version 2

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

 

if(Applications__c.UW_Committed_Deal__c == 'True' && Applications__c.UW_Committed_Deal__c == 'False')

{Task t = new task();
t.Subject = 'UW App Follow-up';
t.OwnerID = Applications__c.Application_Underwriter__r.Id;
t.ActivityDate = Date.today() + 1;
t.WhatId = Applications__c.ID;
t.RecordTypeId = '012E0000000PQRaIAO';
insert t;
}

}


sfdcfoxsfdcfox

UW_Committed_Deal__c cannot be simultaneously 'True' and 'False', so your branch never executes. Also Applications__c.Id is a Schema reference, not a record member value. Your first version is close, but your problem is you have not "bulkified" your code, therefore you're confused why it's not working. Finally, you won't be able to commit your task until the record has been saved, so you should use an "after" DML event, not before. What you probably meant to do is as follows:

 

trigger UWtask on Applications__c (after insert, after insert) {
  Task[] tasks = new Task[0];
  for(applications__c app:trigger.new) {
    if(app.UW_Committed_Deal__c == 'True') {
      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 you're using a checkbox for UW_Committed_Deal__c, remove the quotes around 'True' (or 'False'). If you're NOT using a checkbox, you should be asking yourself why. Anyways, best of luck with your trigger.

babrannobabranno

That worked perfectly.  Thanks for your help.  I am new to writting triggers.  My company doesn't want to pay to get me trained and they also don't want to give me a budget to outsource any development so I am having to hack my way through this.  I appreciate all the help that the community offers.