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
singledotsingledot 

Basic Apex Question from Newbie Unfamiliar with How to Access Reference Fields

Hi. I'm just trying to do a simple trigger but I'm experiencing a lot of frustration with how to actually access reference fields. I'm just triggering the creation of an Event from a custom object insert. Basically, in the custom object Set_Up, there is a lookup field (Pre_Communication__r) that is tied to Users...I'd like that specific user to be assigned the event (i.e. not the current user, etc.). This is what I have:

 

trigger createEvent on laniangela__Set_Up__c (after insert) {
         
       for (laniangela__Set_Up__c suObj:Trigger.new){     
  
             Event evtobj = new Event();
             evtobj.Owner = suObj.Pre_Communication__r;
             evtobj.Subject = 'Pre Communication EVENT';
             evtobj.DurationInMinutes = 60;
             evtobj.StartDateTime = suObj.Pre_Communication_Date__c;
             insert(evtobj);
             
  }
}

 

This is clearly not working. This is the error I receive: Error: Compile Error: Illegal assignment from SOBJECT:User to SOBJECT:Name at line 7 column 14 I'm sure it's something ridiculously easy but I'd really love a pointer here. THANK YOU

Best Answer chosen by Admin (Salesforce Developers) 
Sean TanSean Tan

Well a couple of things. First avoid DML / SOQL in a loop.

 

Second to your error, there are two issues that I see. First, you're assigning it to the "Owner" field which is actually the relationship field to the User table (e.g. Owner.Name or Owner.Id etc...). Instead you want to assign it to the OwnerId field. Secondly you're assigning the relationship value (not lookup value) of the Pre_Communication__c field.

 

Try something like this:

 

trigger createEvent on laniangela__Set_Up__c (after insert) 
{
	Event[] eventList = new Event[]{};
	
	for (laniangela__Set_Up__c suObj:Trigger.new){     		
		Event evtobj = new Event();
		evtobj.OwnerId = suObj.Pre_Communication__c;
		evtobj.Subject = 'Pre Communication EVENT';
		evtobj.DurationInMinutes = 60;
		evtobj.StartDateTime = suObj.Pre_Communication_Date__c;
		eventList.add(evtObj);
	}
	
	insert eventList;
}