【问题标题】:How to insert data into a custom object with lookup field from apex controller如何使用顶点控制器的查找字段将数据插入自定义对象
【发布时间】:2013-12-08 09:29:13
【问题描述】:

我有一个自定义对象MyCustomObj__c,它有一个名为“ContactData”的字段。

我正在尝试使用以下 apex 方法将记录插入到自定义对象中。它给出了一个错误:

Invalid ID

Hari 已存在于联系人列表中。

顶级代码:

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

如何插入一行?

【问题讨论】:

  • 嗨 @Hari,salesforce.stackexchange.com 上有一个专门针对 Salesforce 的新 stackexchange 站点。快来加入那边的社区吧! :)

标签: salesforce visualforce apex


【解决方案1】:

你应该传递联系人记录'Hari'的ID

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

当然,您应该尽量避免使用 SOQL,这只是示例。

【讨论】:

    【解决方案2】:

    将数据插入对象的 Apex 代码:

    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') );
           }
        }
    }
    

    应该打印您刚刚添加的用户的用户名。

    【讨论】:

      【解决方案3】:

      我们可以使用数据加载器将数据移动到数据库中查找字段 大师

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-20
      • 1970-01-01
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      相关资源
      最近更新 更多