DEV Community

GAURAV KUMAR
GAURAV KUMAR

Posted on

2

How to get required fields of an SObject in Apex

Following is the code that can save you time from search on the web- "How to find all the required fields of an SObject in Apex?"

public class DynamicApex {
    public FieldWrapper getFields(String objName) {
        try {
            FieldWrapper wr = new FieldWrapper();
            for (Schema.SObjectField f : Schema.getGlobalDescribe().get(objName).getDescribe().fields.getMap().values()) {
                Schema.DescribeFieldResult r = f.getDescribe();
                if (!r.isNillable() && r.isCreateable() && !r.isDefaultedOnCreate()) {
                    wr.requiredFields.add(r.getName());
                } else {
                    wr.otherFields.add(r.getName());
                }
            }
            return wr;
        } catch (Exception e) {
            throw new TypeException(e.getMessage());
        }
    }

    public class FieldWrapper {
        public List<String> requiredFields;
        public List<String> otherFields;

        FieldWrapper() {
            this.requiredFields = new List<String>();
            this.otherFields = new List<String>();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more