DESCRIPTION
It’s very typical to get such a scenario when we need to create custom field programmatically. Previously, we used to use Metadata API for the same which was very costly.
But now, Tooling API provides an efficient way to achieve it. I’ve prototyped in below class. You can create custom fields as given below.
APPROACH
Below given code is metadata driven, so for each type of field,
- You need to get the metadata. Below is a tip to get metadata.
- You can get required metadata using workbench –> Rest Explorer and hit
/services/data/v48.0/tooling/sobjects/CustomField/00N9000000DHfrM
where ‘00N9000000DHfrM‘ is existing field with same data type. this call will return JSON response where you can extract metadata and manipulate as per your requirement. - You will need to create remote site setting for the given endpoint which is base URL of your salesforce org.
Copy the following utility apex class:
public class MetadataUtility{ public static void generateTextField(String objectAPIName, String fieldAPIName, String fieldDescription, String fieldLabel){ String metadata = '{"Metadata" : {"type" : "Text","description" : "'+fieldDescription+'", "inlineHelpText" : "","precision" : null,"label" : "'+fieldLabel+'","length" : 255,"required" : false}, "FullName" : "'+objectAPIName+'.'+fieldAPIName+'"}'; String responseBody = createField(metadata); } public static void generateFormulaField(String objectAPIName, String fieldAPIName, String fieldDescription, String fieldLabel, String retrunType, String validFormula){ String metadata = '{"Metadata" : {"type" : "'+retrunType+'","description" : "'+fieldDescription+'", "formula" : "'+String.escapeSingleQuotes(validFormula)+'","formulaTreatBlanksAs" : "BlankAsZero","label" : "'+fieldLabel+'"}, "FullName" : "'+objectAPIName+'.'+fieldAPIName+'"}'; String responseBody = createField(metadata); system.debug(responseBody); } public static String createField(String metadata) { HttpRequest request = new HttpRequest(); request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID()); request.setHeader('Content-Type', 'application/json'); request.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v46.0/tooling/sobjects/CustomField'); request.setMethod('POST'); request.setBody(metadata); Http http = new Http(); HTTPResponse res = http.send(request); return res.getBody(); } }
Examples of Usage:
MetadataUtility.generateTextField('Account', 'Type_x__c', 'Text Field created by apex', 'Type (apex)');
//Parameter “validFormula” is important and it should be correct and formated to support JSON.
MetadataUtility.generateFormulaField('Account', 'Ac_Name__c', 'formual Field created by apex', 'Account Name (Formula)', 'Text', '(Name)');
Nope. Method does not exist or incorrect signature: void createHttpRequest(String)…
Sorry! was just copied and pasted from my dev org…now updated it based on your answer in developer forum. Many thanks..
Also this: Non static method cannot be referenced from a static context: System.HttpResponse System.Http.send(System.HttpRequest)
Getting INVALID_SESSION_ID error
[{“message”:”This session is not valid for use with the REST API”,”errorCode”:”INVALID_SESSION_ID”}]
May be you are doing something wrong in your implementation. Just verified below piece of code in developer console and it worked:
HttpRequest request = new HttpRequest();
request.setHeader(‘Authorization’, ‘Bearer ‘ + UserInfo.getSessionID());
request.setHeader(‘Content-Type’, ‘application/json’);
request.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+’/services/data/v41.0/tooling/sobjects/CustomField/’);
request.setMethod(‘POST’);
request.setBody(‘{“Metadata” : {“type” : “Text”,”description” : “ayub”, “inlineHelpText” : “”,”precision” : null,”label” : “Success”,”length” : 255,”required” : false}, “FullName” : “Case.Success__c”}’);
Http http = new Http();
HTTPResponse res = http.send(request);
system.debug( res.getBody());
Am also getting same error
[{“message”:”This session is not valid for use with the REST API”,”errorCode”:”INVALID_SESSION_ID”}]
I have Gone through the above mentioned code i have a query that text fields and formula fields are being created but if i want to create Date,Number,Email,Checkbox etc fields then how can i create that methods please explain or give me some code so that i can also use and see
I have Gone through the above mentioned code i have a query that text fields and formula fields are being created but if i want to create Date,Number,Email,Checkbox etc fields then how can i create that methods please explain or give me some code so that i can also use it and see
amoxicillin clavulanic cost of augmentin can you drink on amoxicillin 500mg what happens when you drink on amoxicillin
So this creates a field but it appears as hidden in the page layout and profile, please share some sample code to change visibility settings via apex?
generic lasix names buy furosemide 20 mg torsemide or furosemide stronger diuretic what is lasix 40 mg used for
azithromycin medscape azithromycin 500mg price in india is zithromax for strep throat how long is azithromycin good for
ivermectin overdose dog ivermectin 3mg price can my dog take ivermectin and revolution what happens too much ivermectin on the body
ipratropium-albuterol can you buy albuterol ventolin hfa 90 mcg inhaler espanol who makes ventolin hfa
Trulife Distribution – Nutrition Distribution helps our clients achieve success in a complex, competitive retail environment. Our team of nutrition industry experts takes care of everything from importation compliance to marketing, sales and distribution at the ground level. There is no need to navigate the complicated intricacies of the American market when we have already done the work. Let us use our experience to expand your brand and put your product into the hands of American consumers. https://trulifedist.com/
In fact when someone doesn’t know then its up to other viewers that
they will help, so here it occurs.
Everyone loves it whenever people get together and share thoughts.
Great website, keep it up! 0mniartist asmr
Simply want to say your article is as amazing.
The clearness in your post is simply great and i could assume you are an expert
on this subject. Fine with your permission let me to grab your RSS
feed to keep up to date with forthcoming post.
Thanks a million and please keep up the enjoyable work.
0mniartist asmr