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
Neil Smith 10Neil Smith 10 

Attach an account object as a lookup on a custom object?

Hi,

I have a custom object (inspection) which has a lookup to the account object. The account object also has a formula field called SPAN. In an Apex class I'd like to create an inspection with a lookup to an account. It's a little weird how the data comes to the class but here it is:

@RestResource(urlMapping='/inspection/*')
global with sharing class InspectionRestController{
   global class RequestBody {
       global Inspection__c inspection;
   }

    @HttpPost
    global static Inspection__c create(InspectionRestController.RequestBody req) {
        Inspection__c newInspection = req.inspection;
        
        if (req.inspection.Account__r != null) {
            String span = req.inspection.Account__r.SPAN__c;
            
            Account account = [select Id from Account where SPAN__c = :span];
            
            newInspection.Account__c.Id = account.Id;
        }
    
        insert newInspection;
        return newInspection;
    }
}

I've tried to attach the account to the inspection in every way possible (new Account(Id = account.Id), etc...). I know I'm getting the correct account by the query because I've logged it out during debugging. 

Any idea what I'm doing wrong?

Thanks
Best Answer chosen by Neil Smith 10
Ajay Nagar 7Ajay Nagar 7
Instead of "newInspection.Account__c.Id = account.Id;" use this
 newInspection.Account__c = account.Id;