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
MLamb2005MLamb2005 

Apex Update of M/D field causing error on insert

Hi all,

I'm struggling to debug the code shown below.  The setup is that there are three custom objects, Employee, Lab Project, and Lab Project Hours.  Each Lab Project Hours record has two master-detail fields, one to Employee and one to Lab Project.  The LPH records are always created from a Lab Project, so I'm trying to update the Employee field programatically.  Each User object has the Salesforce ID of that user's corresponding Employee record.

The intent of this code is, after the user clicks 'Save' to create a new Lab Project Hour record, to find the current user, get their Employee ID from their User record, then put that ID into the Employee Name master-detail field of this new LPH record.

The problem is that it never actually updates, and always gives an "Error: Invalid Data", because it thinks that I've left the Employee Name field blank.  If I roll this field back to a Lookup field it works just fine, but I need the M/D to get Rollup Summary fields.

Please advise.

Thanks,
Matt

Code:
trigger updateEmployeeOnProjectHour on Lab_Project_Hours__c (before insert) {
    
   Id employeePageId = [select Employee_Page__c 
                    from User 
                    where Id = : UserInfo.getUserId() Limit 1].Employee_Page__c;

   for(Lab_Project_Hours__c lb : Trigger.new) {

         lb.Employee_Name__c = employeePageId;
    }
}

 

MLamb2005MLamb2005
So I found this thread: http://community.salesforce.com/sforce/board/message?board.id=apex&message.id=8410

It implies that because I have a Master-Detail relationship setup, and the field is "required", the only way to get around this issue is creating a VisualForce page for the New Record screen when creating a new Lab Project Hour.

Any truth to this?