0

I am using metadata api to create a new custom object and custom fields to that object. I need to make a foreign key referencing Lead Id.

This is my method to create the custom field:

private CustomField createCustomField(String fullName, String description, String label, FieldType fieldType) {
    CustomField customField = new CustomField();
    try {
        customField.setFullName(fullName);
        customField.setDescription(description);
        customField.setType(fieldType);
        customField.setLabel(label);
        customField.setRequired(true);

        if (fieldType.equals(FieldType.Text)) {
            customField.setLength(255);
        }
    } catch (Exception ex) {
        System.out.println("Error creating custom field " + ex.getMessage());
    }
    return customField;
}

I was looking in documentation and don't understand how to create a Lookup type of field and reference to the Lead Id, in order to have a leadId custom field in my object that is direct referencing a lead. Any help will be helpful, thank you.

0

Please try this. Replace Test__c with your object api name and change relationship name/label also.

MetadataService.MetadataPort service = createService();     
MetadataService.CustomField customField = new MetadataService.CustomField();
customField.fullName = 'Test__c.Lead__c';
customField.label = 'Lead';
customField.type_x = 'Lookup';
customField.relationshipLabel = 'Tests';
customField.relationshipName = 'Tests';
customField.referenceTo = 'Lead';
List<MetadataService.SaveResult> results = service.createMetadata(new MetadataService.Metadata[] { customField });        
handleSaveResults(results[0]);
  • This worked only once. If i delete the custom object and run the code again it won't create. Should i find a way to add the lookup in the layout? Or need to delete the lookup from more then one place (delete of custom obj)? – Gabriela Radu Aug 25 '16 at 10:41
  • 1
    You can create this field only once. Because field api name is unique. If you delete the custom object and try this code it will not work. You need to create the object first and then create its fields. – Reshma Aug 25 '16 at 11:36
  • Yes, I delete the object and then create again with the custom fields. What else shall i delete? Thanks – Gabriela Radu Aug 25 '16 at 12:20
  • There is nothing to delete more. If you want to create lookup fields again update the new api name in code. Thats it. – Reshma Aug 30 '16 at 4:27

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.