0

I have a requirement that needs me to do a lookup on a Map based on the value field.

The world object has the following structure.

Name            Type
++++++++++++++++++++++
United States   Country
Pennsylvania    State
Manitoba        Province
Sussex          County

I wish to look up this map by value instead of the key. How can I do lookups based on the Name?

There is another custom object called Mortals, which needs to be updated each time a record is inserted in the world object. I am in the process of writing a trigger on the World object so that it will automatically go lookup the Mortal object, find the records that belong to a certain region and update the lookup field on these records.

The mortal object has the following structure.

FamilyName      Region      World
+++++++++++++++++++++++++++++++++++++++++
Smythe          Germany     <sf_idvalue>
Allgeier        Germany     <sf_idvalue>
Biehle          Dusseldorf  <sf_idvalue>
Binner          England     <sf_idvalue>    

So in this case. If I insert a record that has "Germany", "Country", a trigger will update all corresponding records with this newly created Id for Germany.

I wrote the following code so far.

trigger trg_worldupdate on world__c (after insert, after update) 
{

    Map<string, string> countries = new Map<string, string>();

    for (world__c so : Trigger.new) 
    {
        if(so.Region_Type__c = 'Country')
        {
            countries.put(so.Id, so.Name);
        }
    }
    //Get all records where country is a match
    List<Mortals__c> mortallist = [SELECT Id, Name, World__C FROM Mortals__c WHERE Country__c = :countries.values()];
    for(Mortals__c m : mortallist)
    {
        //how do a lookup over here, since I do not have the key.
        m.world__c = countries.get();
    }

}

How do I go about getting the salesforce id value of the record inserted into world?

1 Answer 1

2

Just invert the map.

Instead of:

countries.put(so.Id, so.Name);

Use:

countries.put(so.Name, so.Id);

Note that if you have multiple records with the same Name, your code will have indeterminate behavior since you don't have any logic to handle collisions. You'll need to determine for yourself whether that's an error case or you want to choose one based on a specific criteria (or arbitrarily).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .