Contents[Hide]

See Salesforce documentation:
Id Instance Methods
SObjectType Instance Methods
DescribeSObjectResult Instance Methods

1. Getting information based on record Id.

Get object name

String objectName = recordId.getSObjectType().getDescribe().getName();

Get object label

String pageTitle = recordId.getSObjectType().getDescribe().getLabel();

Create new object of the same type

sObject newObject = recordId.getSObjectType().newSObject()

Add error message

recordId.addError('Error message with html formatting test. <b> Please contact Admisnitrator </b>', false); 

2. Getting information based on object name.

Schema SObject representation

We can retrive DescribeSObjectResult of concrete SObject directly or indirectly.

Direct way:

Schema.DescribeSObjectResult descResults = MyObjectName__c.SObjectType.getDescribe();

Indirect (dynamic) way, usefull for methods where object name is passed as parameter.

String objectName = 'MyObjectName__c';
Schema.DescribeSObjectResult descResults = Schema.GetGlobalDescribe().get(objectName).getDescribe();

Get object prefix

String userObjectPrefix = Schema.GetGlobalDescribe().get('User').getDescribe().getKeyPrefix();

Get Picklist values

List<Schema.PicklistEntry> picklistValues = Object_Name__c.Field_Name__c.getDescribe().getPicklistValues();
for (Schema.PicklistEntry pe : picklistValues) {
    myStringList.add(pe.getLabel());
}

Generate SOQL query string to query all editable fields.

    private String getQueryStringForAllEditableFields(String objectName) {
        String queryString = 'SELECT ';
        Map<String, Schema.SObjectField> objectFields = Schema.GetGlobalDescribe().get(objectName).getDescribe().fields.getMap();
        
        for (Schema.SObjectField field : objectFields.values()) {
            if (field.getDescribe().isCreateable()){
                queryString += field.getDescribe().getName().trim() + ', ';
            }
        }

        queryString = queryString.removeEnd(', ');
        queryString += ' FROM EMS_Event__c';

        return queryString;
    }

Get Record type Id

Id recordTypeId = MyObjectName__c.getSObjectType().getDescribe().getRecordTypeInfosByName().get('RT name').getRecordTypeId(); // It's Name not Developer name

 

Documentation: apex_class_Schema_PicklistEntry

 

   
© Paweł Woźniak