I have a custom Lightning component which is a simple input form with the Contact fields(required). Obviously the controller class has an insert statement for the Contact sObject.
Is there a way I can create an input component that is not specific to any sObject, and have a Property setup(Design file in the Aura definition bundle) that says: <design:attribute name="objectAPIName" label="sObject"/>
which I can assign any sObject I wanted, and the form should dynamically show the required fields specific to the provided sObject?
Controller to fetch all the fields(Dynamically):
@AUraEnabled
public static List<String> dynamicField(String ObjectName){
String objName = ObjectName;
Schema.SObjectType t = Schema.getGlobalDescribe().get(objName);
SObject s = t.newSObject();
DescribeSObjectResult describeResultPP = s.getSObjectType().getDescribe();
List<String> fieldNamesPP = new List<String>( describeResultPP.fields.getMap().keySet() );
System.debug('Field attributes: ' +fieldNamesPP);
return fieldNamesPP;
}
How can I make use of these fields to populate on the input form? My concern is, I get all the fields of that specific sObject, how can I only display/show required fields to fill in? Also I am not even sure how I can display those on a Lightning.cmp file.
Best Answer
Let me share an overall architecture that I used to accomplish a very similar problem. The first thing I did was to create an apex class
FieldDetail
to model a field describe with@AuraEnabled
get methods for all relevant information like label, data type, etc. Next, aninputField
component was created to consume that information and conditionally render a specific component using$A.createComponent()
depending on the data type. Note that we used bothlightning
namespaced components as well as some components from the strike project. Once we had an input that could render itself for aFieldDetail
, it was simply a task of adding a top level controller that would retrieve a list ofFieldDetail
objects and iterating over them to render ac:inputField
component for each field. In your case that controller may have a method signature similar to:You could then pass the
sObjectName
parameter from either a design attribute or using one of the built in interfaces likeforce:hasSObjectName
and use object and field describes to build your list ofFieldDetail
objects.== Code Sample Update ==
The following class represents the details for a specific field and can be returned from an
@AuraEnabled
method to be consumed in Lightning.You can then construct instances of this class by passing in a record (this could be a new record like
new Contact()
and a list of fields. If you wanted all required fields, you use code similar to