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
asonimieSFDCasonimieSFDC 

Problems creating task with a trigger

I'm trying to create a task using a trigger from a Case.  I'm running into two issues:

 

1. Changing the task to point to the approriate case (apex whatId)

2. Assigning the Task to the case contact (OwnerId)

 

When I try assign OwnerId = Case.Contact I get an error of

Error: Compile Error: Invalid initial expression type for field Task.OwnerId, expecting: Id  

 

As for changing the Related to field to a case and pointing it to the right case, I have no idea how to do that.  It is defaulting to opportunity, I found that the cases all start with 500, but I don't know how that's useful.

Navatar_DbSupNavatar_DbSup

Hi,


Try the below code as reference:


trigger CreateTask on Case (after insert)
{
contact con=[select id,ownerid from contact where id=:trigger.new[0].contactid];
system.debug('@@@@@@@@@@@------------@@@@@@@@@@@@@' +con.ownerid);
task t=new task(subject='call',status='open',activitydate=system.today(),whatid=trigger.new[0].id,ownerid=con.ownerid);
insert t;

}

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

Jerun JoseJerun Jose

Im not an expert at this, but to assign the OwnerID you will have to give the ID of the user.

so the statement should be like

Task ts = new Task();
ts.OwnerID = Case.ContactID;

 The WhatID will also need to be set similarly.

It wil be

ts.WhatID = case.ID;

 

asonimieSFDCasonimieSFDC

This is what I currently have:

 

Task t = new Task(Subject = c.Subject,
        Status = 'Not Started',
        Whatid = c.id,
        Ownerid = c.contactid);

 

The Whatid is working.  but I'm still having trouble with the owner id, I tried contact.id (Cross reference key error) and contactid (FIELD_INTEGRITY_EXCEPTION wrong type).

 

asonimieSFDCasonimieSFDC

I don't think using the contact owner id is an option because the owner of the contact won't always be the same as the contact.

 

Can you explain what you're doing with this:

 

contact con=[select id,ownerid from contact where id=:trigger.new[0].contactid];

 

I understand you're selecting the id and ownerid from the contact, but I don't understand the criteria 'id=trigger.new[0].contactid]

asonimieSFDCasonimieSFDC

When trying to put in the User id, I'm getting a cross reference key error:

 

Error:Apex trigger caseTaskcreate caused an unexpected exception, contact your administrator: caseTaskcreate: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, Assigned To ID: owner cannot be blank: [OwnerId]: Trigger.caseTaskcreate: line 20, column 1