5

I am looking for a way to get the 15 character entity ID for a custom field on my Lead object in an Apex controller. I have tried this:

private String getEntityIdFor(String fieldName) {
        Map<String, Schema.SObjectField> fieldMap = Schema.SObjectType.Lead.fields.getMap();
        return fieldMap.get(fieldName).getDescribe().getId();
    } 

Of course, there is no getId() method, but this is the closest I got.

Thanks for any help.

6

You can get custom field IDs from the tooling API so you should be able to make an HTTPRequest from apex to retrieve this information.

Code should be the following though I haven't tested this:

HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
req.setHeader('Content-Type', 'application/json');

String toolingendpoint = 'http://na1.salesforce.com/services/data/v20.0/tooling/';

//query for custom fields
endpoint += 'query/?q=select+id,DeveloperName,FullName+from+CustomField+limit+1'
req.setEndpoint(endpoint);
req.setMethod('GET')

Http h = new Http();
HttpResponse res = h.send(req);
system.debug(res.getBody());

Note: Unfortunately this only works for custom fields and I don't know of any way to get this same information for standard fields.

|improve this answer|||||
  • A separate http request is a bit too expensive for my application, but very interesting answer! – JannieT Sep 30 '13 at 5:38
1

There's no way to get the SFID for a field in Apex Code. The closest you could attempt to get would be to try and use a PageReference to get the content of the setup screens and perform some screen-scraping, which would be fragile and fairly difficult to implement.

|improve this answer|||||
1

If you guys don't want to use TOOLING API. You can do this.

String prefix = Schema.getGlobalDescribe().get('Account').getDescribe().getKeyPrefix();
PageReference pr = new PageReference('/' + prefix + '/e?nooverride=1');
String html;
Blob pageContent = pr.getContent();
if ( pageContent != null ) {
    html = pageContent.toString();
}
Matcher macher = Pattern.compile('<label for="(.*?)">(<span class="requiredMark">\\*</span>)?(.*?)</label>').matcher(html);
while ( macher.find() ) {
    String label = macher.group(3);
    String fldId = macher.group(1);
    system.debug(label+'############'+fldId);
}

Hit vote up if this helps you. Happy coding... :)

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.