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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn 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

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay