简体   繁体   中英

Salesforce: Cannot update lookup field value with trigger

I'm just trying to update a lookup field value (Campagna_Account__c) on Account object using a trigger that should update it getting the value from a custom object (Sottocampagna__c). I think the query is right because it runs well on Force.com Explorer, so I think the problem is somewhere else.

Here's the error line displayed when trigger fires:

data changed by trigger for field Campagna: id value of incorrect type: a06250000004FDNAA2

Here's my code:

trigger PopolaCampagna on Account (before insert, before update) {

    Sottocampagna__c var = [

        SELECT Campagna__r.Id 
        FROM Sottocampagna__c
        WHERE Name='Segugio'

        ];

for (Account a: Trigger.new) {

        a.Campagna_Account__c = var.Id;
    }    
}

Thank you for helping me!

You are trying to assign Sottocampagna__c record's id into a.Campagna_Account__c using this code. You should change it to be:

for (Account a: Trigger.new) {

    a.Campagna_Account__c = var.Campagna__r.Id;
}    

}

Another thing which I would recommend is to change this query to:

Sottocampagna__c var = [

    SELECT Campagna__r.Id 
    FROM Sottocampagna__c
    WHERE Name='Segugio' limit 1

    ];

It will prevent exceptions if there are more than 1 record which suits query criteria. If you are not comfortable with this behaviour and potentially you could have multiple records which suits criteria it is better to use List<>. Let me know if it helps.

Also some tips on naming conventions: https://salesforce.stackexchange.com/questions/890/what-is-a-good-set-of-naming-conventions-to-use-when-developing-on-the-force-com

Actually this should also work:

    for (Account a: Trigger.new) {

    a.Campagna_Account__c = var.Campagna__c;
}    

}

Sottocampagna__c var = [

    SELECT Campagna__c 
    FROM Sottocampagna__c
    WHERE Name='Segugio' limit 1

    ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM