0

Let's say we have a Map<String,Object> we got from an lwc, and we need to create records for any given SObject that can change based on some custom metadata type records.

I have the following snippet but always get an error like invalid runtime conversion from type String to Schema.DisplayType

SObject record = (SObject) Type.forName(objectName)
     .newInstance();
 String fieldType = String.valueOf(record.getDescribe().fields
    .getMap()
    .get(fieldName)
    .getDescribe()
    .getType());
    Type displayType = Type.forName(fieldType);
     record.put(
        objectField, //name of the field
         (displayType) mapStringObjectWithMyValuesFromLWC.get(objectField)
     );

I may be missing a better approach. All help and input is appreciated :(

1 Answer 1

4

The getType method you are calling directly returns a DisplayType value rather than a String so change your code to:

DisplayType displayType = record.getDescribe().fields
    .getMap()
    .get(fieldName)
    .getDescribe()
    .getType();

See the DescribeFieldResult documentation for more detail.

PS

In response to the first comment, in your approach, you are running Type.forName on one of the enum values e.g. DisplayType.Picklist not the enum type DisplayType. So it's not going to work even if Apex treated enum as a special kind of class.

Also note that trying to cast a field value to a DisplayType won't work. For types other than strings you will likely need to write your own type conversion code based on the DisplayType or likely better based on the SOAPType that is also available from a describe call.

Given this complexity do consider if your overall approach here is appropriate.

2
  • I'm sorry for the confusion; I saw that I did not post the correct example of what I'm trying to do; yes, the last getType returns a Schema.DisplayType, but I was trying to get the string value and pass it down to the forName method of the Type class. This is constantly breaking on the type casting.
    – SouthJoe
    Jan 10 at 12:52
  • @SouthJoe I've added a PS to my original answer that I hope helps.
    – Keith C
    Jan 11 at 10:03

You must log in to answer this question.

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