How to insert data into a custom object with lookup field from apex controller

Hari Das picture Hari Das · Nov 23, 2013 · Viewed 17.7k times · Source

I have a custom object MyCustomObj__c which has a field called "ContactData".

I am trying to insert a record into the custom object with the following apex method. It gives an error:

Invalid ID

The value Hari already exists in the Contact list.

apex code:

public static String saveData(){
    MyCustomObj__c newObj = new MyCustomObj__c(); 
    newObj.contactData__c = 'Hari';
    insert newObj;
    return "success";
}

How do I insert a row?

Answer

Pavel Slepiankou picture Pavel Slepiankou · Nov 24, 2013

you should pass ID of contact record 'Hari'

 public static String saveData(){
       MyCustomObj__c newObj = new MyCustomObj__c(); 
       newObj.contactData__c = [SELECT Id 
                                FROM Contact 
                                WHERE Name ='Hari' LIMIT 1].Id;
       insert newObj;
       return "success";
 }

Sure, you should try to avoid SOQL here, it's just example.