I found this question very interesting: Programmatically Determine Which Objects Allow Lookup References to Them?

In my naiveté, I thought perhaps this question could be answered by using the Tooling API to try creating a lookup field to each standard object type and then see which types fail. Unfortunately, the FieldDefinition type does not support the create operation via SOAP, nor does it support POST requests via REST.

At least...so the documentation claims. I was able to create a field via the REST API in Workbench and also using an Execute Anonymous script:

class Field
    String FullName;
    FieldMetadata Metadata;
class FieldMetadata
    String referenceTo, relationshipName;
    String deleteConstraint = 'SetNull';
    String relationshipLabel = 'Demo';
    String type = 'Lookup';
    String label = 'Demo';
    Boolean required = false;

Field lookup = new Field();
lookup.Fullname = 'MyObject__c.Lookup__c';
lookup.Metadata = new FieldMetadata();
lookup.Metadata.referenceTo = 'User';
lookup.Metadata.relationshipName = 'Children';

String payload = JSON.serialize(lookup);
String endpoint = URL.getSalesforceBaseUrl().toExternalForm() +
String auth = 'Bearer ' + UserInfo.getSessionId();

HttpRequest request = new HttpRequest();
request.setHeader('Authorization', auth);
request.setHeader('Accept', 'application/json');
request.setHeader('Content-Type', 'application/json');
new Http().send(request);

This discovery seemed like great progress, but in order to really use this approach to solve the problem at hand (answering which standard objects support lookup relationships programmatically), I would need to be able to delete the resulting fields or create new object types, since only 40 relationship fields are allowed on each object.

It seemed easier to just create a new object, which led me to this question: Possible to create a new sObject with Tooling API REST interface? Someone astutely noted in the comments that the EntityDefinition describe lists createable as false. Indeed the same holds for FieldDefinition:

FieldDefinition Describe

And yet, I can successfully insert a FieldDefinition. What gives? Is this behavior a bug?

For what it's worth, I was not able to make a DELETE request against this object, nor was I able to POST to EntityDefinition.

Your Answer

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

Browse other questions tagged or ask your own question.