1

I am loading my fields dynamically trough a fieldset. Using aura:id="requiredField" on the lightning:inputField I can get the fields using a map in the controller. I have made some fields required at fieldset level not at fieldlevel. How can I get these values in the controller to validate only on the required fields? Or how can I get the attributes for a specific field. Using required is returning empty.

Component

  <lightning:card title="{!v.title}" iconName="{!v.iconName}" class="slds-p-around--none">        
        <lightning:recordEditForm aura:id="recordViewForm" 
                                  recordId="{!v.recordId}"
                                  objectApiName="{!v.genericObject}"
                                  onsubmit="{!c.fireRefreshView}"
                                  onerror="{!c.handleError}"
                                  class="slds-p-around--small">
             <lightning:messages />


                        <aura:iteration items="{!v.fields}" var="field">
                <aura:if isTrue="{!v.inputModeBool == true? true: false}">
                    <lightning:inputField fieldName="{!field.fieldPath}"    aura:id="requiredField" />{!field.required}  <!-- class="customRequired"-->

Controller

next: function (component, event, helper) {
        var recUi = component.get('v.recordId');   
        alert('recUi: '+recUi);
    var Fields = component.find('requiredField').map(function (i) {
        return i.get('v.fieldName') });
          alert('Fields: '+Fields);
       var FieldValue = component.find('requiredField').map(function (i) {
            return i.get('v.value');   });
        alert('FieldValue: '+FieldValue); 
            var FieldRequired = component.find('requiredField').map(function (i) {
            return i.get('v.required');   });
        alert('FieldRequired: '+FieldRequired); 
2

enter image description here

Try as below (main point is having custom class and styling it). Also for validations, you need iterate over all fields and check which are required, and then check if that field has value

Aura comp:

<aura:component controller="poc" implements="lightning:isUrlAddressable" >

    <aura:attribute name="fields" type="List" default="[]" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />

    <div class="slds-theme_default">
            <lightning:recordEditForm aura:id="form" 
                                      recordId="00128000009j45qAAA"
                                      objectApiName="Account">
                <!-- the messages component is for error messages -->
                <lightning:messages />

                <aura:iteration items="{!v.fields}" var="fld">
                    <lightning:inputField aura:id="field"
                                          fieldName="{!fld.fieldPath}"
                                          class="{!if(fld.required,'poc-required','')}"/>
                </aura:iteration>
                <div class="slds-m-top_medium">
                    <lightning:button variant="brand" 
                                      name="save" 
                                      label="Save"
                                      onclick="{!c.submit}"/>
                </div>
            </lightning:recordEditForm>
    </div>

</aura:component>

JS:

({
    doInit : function(component, event, helper) {
        let action = component.get("c.getFieldsFromFieldSet");
        action.setParams({
            objectName: "Account",
            fieldSetName: "POC"
        });
        action.setCallback(this, function(response){
            let state = response.getState();
            if(state==="SUCCESS"){
                let fieldsStr = response.getReturnValue();
                console.log("fields => ",fieldsStr);
                let fields = JSON.parse(fieldsStr);
                component.set("v.fields", fields);
            } else {
                alert("error");
            }
        });
        $A.enqueueAction(action);
    },
    submit : function(component, event, helper) {
        event.preventDefault();
        let fields = component.find("field");
        let isValid = !fields.find(fld => $A.util.hasClass(fld,"poc-required") && !fld.get("v.value"));
        if(isValid) {
            component.find("form").submit();
        } else {
            let invalidFields = fields.filter(fld => $A.util.hasClass(fld,"poc-required") && !fld.get("v.value"));
            console.error("invalidFields => ", JSON.stringify(invalidFields));
        }
    },
})

Styles:

.THIS .poc-required label::before{
    content: "* ";
    color: red;
}

Apex class method:

@AuraEnabled(Cacheable=true)
public static String getFieldsFromFieldSet(String objectName, String fieldSetName)
{
    Schema.DescribeSObjectResult sObjectDescribe = 
        Schema.getGlobalDescribe().get(ObjectName).getDescribe();

    Schema.FieldSet fieldSet = sObjectDescribe.FieldSets.getMap().get(fieldSetName);

    System.debug('fields => '+fieldSet.getFields());
    return JSON.serialize(fieldSet.getFields()); 
}
2
  • Thanks for explaining. In this example how do I alert on the fields that did not validate? – Thomas Jul 28 '19 at 17:32
  • added logic for invalidFields in answer – salesforce-sas Jul 29 '19 at 13:53
0

How to validate required fields on JS

  1. Create new aura:attribute
<aura:attribute name="requiredFields" type="List" default="[]" access="private" />
  1. Init this attribute just after setting fields
component.set('v.requiredFields', fields.filter(el => el.required).map(el => el.fieldPath));
  1. You should use button of submit type in the body of lightning:recordEditForm. Example:
<lightning:recordEditForm aura:id="recordViewForm" 
    recordId="{!v.recordId}"
    objectApiName="{!v.genericObject}"
    onsubmit="{!c.handleSubmit}"
    onerror="{!c.handleError}"
    class="slds-p-around--small">

    <lightning:button type="submit" label="Save" />

</lightning:recordEditForm>

onsubmit="{!c.handleSubmit}"

  1. Override standard submit functionality
handleSubmit: function(component, event, helper) {
    event.preventDefault();
    let fields = event.getParam('fields');
    let isValid = true;
    let validationError = '';
    for(let requiredField of component.get('v.requiredFields')) {
        if($A.util.isEmpty(fields[requiredField])) {
            // Required field is empty
            isValid = false;
            validationError = requiredField + ' is blank!'
            break;
        }
    }
    if(isValid) {
        component.find('recordViewForm').submit(fields);        
    } else {
        //Show validation error
    }
}
0

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.