1

What I have in my custom controller is an assignment when a user inputs a value for a certain field, the field for its parent object will update as well.

For example.

User inputs the school for a scholarship recipient through <apex:inputField>. Both scholarship and recipient have required fields for the school__c field, so I need to update the school field on the scholarship record to be dynamically the same as the school that the user inputted for recipient__c

What I have attempted:

    public with sharing class regularController {
    
    public Scholarship_Award__c sch {get;set;}
    public Recipient__c rec {get;set;}
    
    //Constructor
    public regularController(){
    sch = new Scholarship_Award__c();
    rec = new Recipient__c();
    }
    
    public void saveScholarship(){
        insert rec;
        sch.Recipient__c = rec.Id;
        sch.School__c = rec.School__r;
        insert sch;
        sch = new scholarship_award__c(Recipient__c=rec.Id);
        rec = new recipient__c(School__c=sch.School__r);
    }
}

Which returns the error:

A non foreign key field cannot be referenced in a path expression: School__c

on line 18 which is the line of code that sets the school__c field on the recipient object to the value inputted in scholarship_award__c:

        rec = new recipient__c(School__c=sch.School__c.Id);

1 Answer 1

2

It's just __c. No need to go through the relationship:

rec = new recipient__c(School__c=sch.School__c);

If you actually needed a value from the related object, you'd use __r instead:

rec = new recipient__c(Name=sch.School__r.Name);
8
  • Thank you. However when I change __c to __r, it returns the following error: Illegal assignment from School__c to Id - __c seems to work OK however it needs a value from the related object Sep 26, 2020 at 21:43
  • See updated code on my post Sep 26, 2020 at 21:43
  • @patriciajlim Correct, __c or __r.Id. I would recommend the first method, as it's less code and CPU time.
    – sfdcfox
    Sep 27, 2020 at 0:13
  • Thanks. I am still receiving the error Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [School]: [School] Error is in expression '{!saveScholarship}' in component <apex:commandButton> in page testpage: Class.regularController.saveScholarship: line 15, column 1 With this setup - I have hidden the School__c field from recipient__c object, but I need to prepopulate this value in the background. Sep 28, 2020 at 17:34
  • @patriciajlim you'll need to set it in your controller before saving.
    – sfdcfox
    Sep 28, 2020 at 17:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .