Giosuè Zocco
Giosuè Zocco

Reputation: 1

Create a method that convert a List<SObject> to a Map<SObjectField, SObject> with SObjectField as method parameter, any suggestions?

global with sharing class test1 {
global Map<SObjectField, SObject> ConvertMap(List<SObject> listToConvert){
    List<SObject> listToConvert = new List<SObject>;
    Map<SObjectField, SObject> mapTest = new Map<SObjectField, SObject>;
    mapTest.putAll(listToConvert);
    return mapTest;
}

I've written this code, but it doesn't respect the request 'cause I can't put SObjectField as method parameter since the Map won't recognize the variable. Does anyone have suggestions on how to do it? Thank you in advance.

Upvotes: 0

Views: 2451

Answers (2)

Abhinav bhardwaj
Abhinav bhardwaj

Reputation: 2737

To create a map of sObject field you first need to craete a map of all fields of that object for example you want a map like

Map<SObjectField, String> registrationAttributes=  new Map<SObjectField, String> ();

for that

// Get a map of all of the fields on the 'User' object
Map<String, Schema.SObjectField> fMap = Schema.getGlobalDescribe().get('User').getDescribe().Fields.getMap();
// Get details from the field
Schema.SObjectField FirstName = fMap.get('FirstName');

registrationAttributes.put(FirstName, 'Abhinav');
  for (SObjectField field : registrationAttributes.keySet()) {
                String value = registrationAttributes.get(field);
                system.debug('field ==> '+ field);
                system.debug('value ==> '+ value);
 }

Upvotes: 0

eyescream
eyescream

Reputation: 19637

Do you really need SobjectField as map keys? the special class? If you're fine with strings as keys then there's a builtin, getPopulatedFieldsAsMap()

If you absolutely need SobjectField (I don't even know if it's serializable and can be passed to integrations, LWC etc)... You'd have to loop and marry the results to something like

Schema.describeSObjects(new List<String>{'Account'})[0].fields.getMap()

Upvotes: 1

Related Questions