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
Hanna BergsmaHanna Bergsma 

Updating Lookup Field with Apex: DML requires SObject or SObject list type: Id

I have orders that are created via API where the State Code field is populated but the lookup field to State Information Object is not.

Id like to look up the ID of the State information record that corresponds with the state code. The state information object has a state code field on it as well to match with the order state code

Here is what I have so far, getting a "DML requires SObject or SObject list type: Id" error
trigger fillStateRelationship on Order (before insert, before update) {
    
    for (Order myOrder : Trigger.new){
        if (myOrder.State_Filed_In__c == null && myOrder.State_Code__c != null)  {
        
        String stateCode = myOrder.State_Code__c;
        }   
    	State_Information__c state = [select Id from state_information__c where state_code__c =: myOrder.State_Code__c limit 1];
    	String stateId = state.id;
   		update myOrder.State_Filed_In__c  = stateId;
		}
      }

 
Best Answer chosen by Hanna Bergsma
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Hanna,

Please update the code as below. 

I have removed the Update statement at last as it is before Context no need to mention Update statement. Also replaced the String Stateid with ID StateId
trigger fillStateRelationship on Order (before insert, before update) {
    
    for (Order myOrder : Trigger.new){
        if (myOrder.State_Filed_In__c  == null && myOrder.State_Code__c != null)  {
        
        String stateCode = myOrder.State_Code__c;
        }   
    	State_Information__c state = [select Id from state_information__c where state_code__c =: myOrder.State_Code__c limit 1];
    	Id stateId = state.id;
   		 myOrder.State_Filed_In__c   = stateId;
		}
      }
If this solution helps, Please mark it as best answer.

Thanks,
 

All Answers

Sai PraveenSai Praveen (Salesforce Developers) 
Hi Hanna,

Please update the code as below. 

I have removed the Update statement at last as it is before Context no need to mention Update statement. Also replaced the String Stateid with ID StateId
trigger fillStateRelationship on Order (before insert, before update) {
    
    for (Order myOrder : Trigger.new){
        if (myOrder.State_Filed_In__c  == null && myOrder.State_Code__c != null)  {
        
        String stateCode = myOrder.State_Code__c;
        }   
    	State_Information__c state = [select Id from state_information__c where state_code__c =: myOrder.State_Code__c limit 1];
    	Id stateId = state.id;
   		 myOrder.State_Filed_In__c   = stateId;
		}
      }
If this solution helps, Please mark it as best answer.

Thanks,
 
This was selected as the best answer
Hanna BergsmaHanna Bergsma
Thank you!! It worked as desired