1

I'm doing a query to an sObject with Dynamic apex and I would like to store al keys and values in a map where the map contains the object field as key and the value of that field from my query looking something like this:

Map<String,String> mapFieldQueryValaue = new Map<String,String>();

List<sObject> objectList = Database.query('Select Id,Name from Account');

for(sObject record:objectList){
      mapFieldQueryValaue.put(sobjectField[dinamyc inject object field Name],record.Name);
     //the map content would look like (Name = 'testName',Email='test@email.com')   
}

There's a way to store the FieldName as my key?

  • 4
    check this post salesforce.stackexchange.com/questions/113238/… – Ratan Paul Mar 7 '16 at 16:17
  • 2
    Assuming you do need the separate map and that you do want all the values to be strings (JSON.deserialise will not guarantee that) you can get all the possible field names from the DescribeSObjectResult and loop over those putting the String.valueOf of each non-null value into your map. Or just hard code "Id" and "Name" if that is all you need. – Keith C Mar 7 '16 at 16:20
  • @KeithC You will probably have some issues with String.valueOf(null), since that returns 'null'. – Adrian Larson Mar 7 '16 at 16:24
  • @AdrianLarson I did say "of each non-null value"... – Keith C Mar 7 '16 at 16:26
  • @KeithC Good call, I didn't see that part of your comment. – Adrian Larson Mar 7 '16 at 16:26
3

Generic code to query all fields and put them into a Map<String,String> is:

// Works for any SObjectType
SObjectType sobType = Account.SObjectType;

Map<String,String> m = new Map<String,String>();
List<String> fields = new List<String>(sobType.getDescribe().fields.getMap().keySet());
for (SObject sob : Database.query(''
        + ' select ' + String.join(fields, ',')
        + ' from ' + sobType
        + ' limit 1'
        )) {
    for (String field : fields) {
        Object value = sob.get(field);
        if (value != null) m.put(field, String.valueOf(value));
    }
}
System.debug(m);

A list of maps would be needed to deal with multiple rows.

| improve this answer | |
0

To dynamically get a field value you can use the get property.

This is how you'd use it.

mapFieldQueryValaue.put(record.get(*<yourfieldname>*),record.Name);

I would cast that to a string/number/whatever, if you can.

| improve this answer | |

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