4

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?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Hari Das
  • 10,145
  • 7
  • 62
  • 59
  • 2
    Hi @Hari, there is a new stackexchange site specific to Salesforce at salesforce.stackexchange.com. Come join the community over there! :) – Ralph Callaway Nov 25 '13 at 18:13

3 Answers3

5

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.

Pavel Slepiankou
  • 3,516
  • 2
  • 25
  • 30
0

Apex Code to insert data into an object:

static void testInsert(){
    User testUser = new User(username = 'joebieber@hotmail.com', 
    firstname = 'joe', lastname = 'bieber', 
    email = 'joebieber@hotmail.com', Alias = 'jo', 
    CommunityNickname = 'jo', 
    TimeZoneSidKey = 'America/New_York', LocaleSidKey = 'en_US', 
    EmailEncodingKey = 'ISO-8859-1', 
    ProfileId = '00e6000000167RPAAY', 
    LanguageLocaleKey = 'en_US');
    insert testUser;

    List<SObject> sos = Database.query('select username from User');

    List<User> users= new List<User>();
    if( sos != null ){
       for(SObject s : sos){
          if (((User)s).get('username') == 'joebieber@hotmail.com')
            Utils.log('' + ((User)s).get('username') );
       }
    }
}

Should print the username of the user you just added.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
0

We can use data loader for moving data to database for lookup field Guru

guru
  • 1
  • 1
    Thanks for taking the time to contribute an answer. It’s because of helpful peers like yourself that we’re able to learn together as a community. [Here are a few tips on how to make your answer great](http://stackoverflow.com/help/how-to-answer) – JasonWilczak Jun 11 '15 at 15:38