【问题标题】:How to set a Lookup Field via a Salesforce Trigger如何通过 Salesforce 触发器设置查找字段
【发布时间】:2013-05-22 18:56:19
【问题描述】:

我想使用 salesforce apex 触发器设置查找字段,但我不断收到错误消息:

System.StringException: Invalid id:

我有一个名为Job__c 的自定义对象。它有一个自定义的帐户选择列表:Acct__c

用户将Acct__c 填充为John Deer,触发器应将John Deer 添加到Account__c 查找字段。

这里是触发器:

trigger UpdateAccounts on Job__c (before insert) {
    for (Job__c obj: trigger.new){
        obj.Account__c = obj.Acct__c;           //Exception is thrown here
}

抛出异常:

System.StringException: Invalid id:

我尝试了一些不同的方法:

List <Job__c> opListInsert = new List<Job__c>();
List <Job__c> opListUpdate = new List<Job__c>();
if(trigger.isInsert){
    for(Job__c op:trigger.New){
        if(op.Acct__c != Null){
            op.Account__c = op.Acct__c;
            opListInsert.add(op);
        }
    }
}
else if(trigger.isUpdate){
    for(Job__c op:trigger.New){
        if(op.Acct__c != Null && op.Acct__c !=trigger.oldMap.get(op.id).Acct__c){
            op.Account__c = op.Acct__c;
            opListUpdate.add(op);
        }    
    }
}

该代码抛出:

Error:Apex trigger UpdateAccounts caused an unexpected exception, contact your 
administrator: UpdateAccounts: execution of BeforeUpdate caused by: 
System.StringException: Invalid id: 

它告诉我这是一个无效的 ID,我做错了什么?

【问题讨论】:

    标签: triggers salesforce visualforce


    【解决方案1】:

    Account__c 是一个查找字段,您不能为其分配字符串(选项列表字段)。相反,您必须为其分配一个帐户 ID。

    我不确定您为什么在选项列表字段中使用帐户名称,但如果您想继续这样做,那么有一个简单的解决方案,即帐户名称是唯一的。

    获取 id 查询中所选帐户的 id,如下所示:

    list<account> acclist = [select id from account where name In yourNameList];
    

    然后在触发器中引用id

    obj.account__c = accList[0].id;
    

    利用maps,不要在for循环里面加soql

    【讨论】:

    • 谢谢。它用于用户可以选择帐户的外部 VF 页面。否则,用户需要直接在帐户字段中输入数据,但我们不希望他们查看所有帐户(因为不要将帐户查找直接放在 VF 页面上)。不干净,我知道。有什么建议吗?
    【解决方案2】:

    您必须使用您希望它链接到的对象的 ID 设置您的字段。

    salesforce 浏览器页面有一个方便的工具,可让您将不完整的信息输入到查找字段中,然后它会自动为您填写。当使用 apex 语句手动分配值时,不会发生这种情况。您只能将该值设置为查找设置为链接到的对象的有效且现有 ID。

    此代码将获取ID 给定的name 并执行您想要的操作:

    trigger UpdateAcct on Job__c (before insert, before update) {
    
        List<String> Accounts = new List<String>(); 
        for (Job__c obj: trigger.new){
            Accounts.add(obj.Acct__c);
        }
    
        list<Account> acctlist = [select Name from account where Name in :Accounts];
    
        if (acctlist.size() > 0 ){
    
            for (Integer i = 0; i < Trigger.new.size(); i++)
            {
    
                if (Trigger.new[i].Acct__c != null)  
                {
                    Trigger.new[i].Account__c = acctlist[i].ID; 
                }   
                else
                {
                    Trigger.new[i].Account__c = null;
                }
            }
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-29
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多