[SalesForce] Setting attribute required to lightning:inputField

in Salesforce classic I created an object ,Equipment__c' and the field ,License plate' amongst others. We are using the object ,Equipment__c' for different types of equipment. For trucks the field ,License plant' must be mandatory. For tanks, however, it must not be visible. Therefore, the field ,License plate' is not required on database level. Rather, we created different visualforce pages and made the field mandatory in within the page.

Now we would like to move to Salesforce lightning with our application. I tried to use lightning:recordEditForm and lightning:inputField because then the fields are bound to the object's field and dependent picklists are working fine. However, we are facing two issues:

  1. Lookup fields can be displayed but when I try to search the spinner keeps spinning within the field and nothing happens. Does anyone has an idea why this happens?

  2. Is there any way to make a lightning:inputField mandatory even though it is not mandatory on database level? I tried to manipulate the input field via javascript but this isn't possible because of the locker service.

Best Answer

maybe I found a solution to the problem. This is what I have set up:

  1. In the object manager do not set the field in question to required. Rather, create a validation rule that checks for blank values.
  2. In your component bundle create the following styles.

    .THIS .customRequired{
     font-weight: 400; } .THIS .customRequired:before{    
     content: "*";
     margin: 0 0.125rem 0 0.125rem;
     color: rgb(194, 57, 52);
     float: left; } .THIS .none{
     display:none; }
    
  3. In your controller create the following function

    showRequiredFields: function(component, event, helper){
    $A.util.removeClass(component.find("Input_contract_type__c"), "none");
    },
    
  4. In your component create a recordEditForm and set the onload function. Also, create and inputField and set the class attribute.

    <lightning:recordEditForm onload="{!c.showRequiredFields}" aura:id="editForm" recordId="{!v.recordId}" objectApiName="Contract__c"> <lightning:inputField class="customRequired none" aura:id="Input_contract_type__c" fieldName="Contract_type__c" />

The css styles create a red star as label prefix. I figured out that if the star is not hidden on init, it will be displayed before the other fields are displayed. Therefore, I the star is hidden during init and is displayed onload.

Related Topic