0

I have a requirement to fetch Contact Region from Contact and update the same on User.

Here is my logic:

list<user> user = [SELECT name,Region__c from User where isactive = true];
  Set<string> str = new Set<string>();
        for(user u1 : user){
            str.add(u1.name);
        }

        List <Contact> Contact = [
 select id,Salesforce_User__c,Contact_Region__r.name  from contact where Contact_Region__c != null];
                                      
                                      
        Map<id, list<String>> usertcMap = new Map<id, list<String>> ();
        for (Contact Contacts : Contact) {
            if(!usertcMap.containsKey(Contacts.Salesforce_User__c))
                usertcMap.put(Contacts.Salesforce_User__c, new list<string>{Contacts.Contact_Region__r.name});
        else
            usertcMap.get(Contacts.Salesforce_User__c).add(Contacts.Contact_Region__r.name);
        }
        list<User> userupdates = new list<user>();
        for(User us : user){ 
            if(usertcMap.containsKey(us.id))
            {
                 
                list<string> allProsList =usertcMap.get(us.id);
                us.Region__c = allProsList;
                userupdates.add(us);
            }
        }

        if(!userupdates.IsEmpty())
            update userupdates;

now when i am trying to run the above logic, i am seeing this error:

Illegal assignment from List<String> to String

Can anyone please let me know how to overcome this error?

Thanks!

2

I think your error might be on this line:

us.Region__c = allProsList;

Region__c might be a text field in backend and you are trying save a list in that. Now if you need to add the list of regions at once in Region__c, then you might need to JSON.serialize and then convert to string and add.

Note: Make sure the length of the text field does not exceed the data. Or you can use long text area if you are sure there can be more data.

2
  • 1
    @Narendra, The region values which i am trying to add are like USA, AUS. And each record only holds one region value. How to get only one value for each record from that list? Or is there anyway where i can get contact’s region to user region? Please suggest – SFDCUser Jun 18 at 8:42
  • Every user will have only one contact right. So why are you expecting user's region in list , i.e. usertcMap can be map of user id and region. You can convert that to single value and then add that to User's region. – Nagendra Singh Jun 18 at 9:02
0

You need to join the list of String into a single string like this.

us.Region__c =  String.join(allProsList, ',' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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