Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Salesforce by (11.9k points)

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?

1 Answer

0 votes
by (32.1k points)
edited by

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";

 }

Want to become a Salesforce expert, join Salesforce Online Training now!

Browse Categories

...