3

I'm trying to use sObject to dynamically change Name field objects across while organization.

I've tried using SomeId.getSObjectType().newSObject(SomeId) to create the sObject, but when I try to change the Name field I have error

Variable does not exist: Name

Map<Id, string> idsToUpdate = new Map<Id, string>();

// Put the Id's and associated name values in the map

List<SObject> sObjectsToUpdate = new List<SObject>();

foreach(Id idToUpdate : idsToUpdate.keySet) {
    SObject o1 = idToUpdate.getSObjectType().newSObject(idToUpdate);
    o1.Name = idsToUpdate.get(idToUpdate);
    sObjectsToUpdate.add(o1);
}

update sObjectsToUpdate;

As I can see other posts, this is the way of creation dynamic update of objects.

Any idea why this happens?

Brane
  • 3,257
  • 2
  • 42
  • 53

1 Answers1

4

Not all objects have a name field, you should check for the existence of the name field before trying to set the field also you must use the put method

Map <String, Schema.SObjectField> fieldMap = o1.getSobjectType().getDescribe().fields.getMap();
if(fieldMap.containsKey('Name')){
    o1.put('Name', 'Test');
}
Gareth Jordan
  • 968
  • 1
  • 6
  • 10
  • I know that, I just get that field as example. p.s I have custom field that is placed in every object which will be used. – Brane Oct 08 '18 at 16:58
  • Then you should check that your user/profile has access to the field in question via FLS, but in your code you have o1.Name = ..., it should be o1.put('Field_Name__c', 'Value');. You cant access the fields directly using the dot Notation it must be as a map – Gareth Jordan Oct 08 '18 at 18:21