I'm writing some code which will insert the Id of a Target__c (custom object) record into a field called Target__c in the Master Detail field of a junction object TargetxOpp__c.

The Identifier fields contain a key which enables me to match an Opportunity record with a Target__c record.

When I try to fetch the Target__c record Id from a map, in this line

Target__c t1 = targets.get(opp.Identifier__c);

I get the following error message

Illegal assignment from Id to Target__c

Since the error message doesn't state 'SObject:Target__c' I think my code's confusing the reference to the custom object Target__c with the custom field on the TargetxOpp__c object - Target__c.

I'm guessing that there's a way to avoid this confusion without renaming the field but I'm not sure how to?

Here's my code, to keep it short, I've left out the first part of the code which just creates a list of Opportunity's with a specific record type, to work with.

trigger NewOpportunityTarget on Opportunity (after insert) {

        Set<String> identifiers = new Set<String>();
        for(Opportunity o1 : oppIds){

        //create map of target records with an identifier that matches the Opportunity's
        map<String,Id> targets = new map <String,Id>();
        for(Target__c t: [SELECT Identifier__c, Id FROM Target__c
                           WHERE Identifier__c in :identifiers])
            targets.put(t.Identifier__c, t.Id);

        List<TargetxOpp__c> newLinks = new List<TargetxOpp__c>();
        for(Opportunity opp : oppIds){

            TargetxOpp__c j = new TargetxOpp__c();

            // fetch Id of Target record, based on Opportunity identifier
            Target__c t1 = targets.get(opp.Identifier__c);

            j.Opportunity__c = opp.Id;
            j.Target__c = t1.Id;

        insert newLinks;

The error you are making is that you are trying to retrieve a Target__c object from a map that only contains Id's.

If you need the complete Target__c record instead of the Id, you need to put the Target__c record in the map (and not the Id). So like this:

map<String,Target__c> targets = new map <String,Target__c>();
for(Target__c t: [SELECT Identifier__c, Id FROM Target__c
                           WHERE Identifier__c in :identifiers])
    targets.put(t.Identifier__c, t);

Alternatively, if you only need the Id, then don't assign to a Target__c record but to an Id:

Id t1Id = targets.get(opp.Identifier__c);


j.Target__c = t1Id;
  • Apologies, I was too quick to comment, I figured out the cause of both issues. – Alex S Jun 16 '15 at 11:40
  • ok, no problem :-) – Guy Jun 16 '15 at 11:42

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.