function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Abby StockerAbby Stocker 

Required field via apex

Hello! 
There is code (that I did not originally write) that I have been digging through to try to find out how to make a field required. What this code is doing: On a case, the user can select an option to "Tag Images". This will take them to a component and they can fill out specified fields. After the select "Submit", this will create a Case File record and it will be linked to the case. On the component screen, there are about 6 fields. Two of them need to be required to move forward. One is currently required and I will provide screenshots below.
They select a photo to tag:
User-added image
They then get taken to a screen to fill out information about the image(s). Primary Reason (Return_Reason__c) and Secondary Reason (Return_Reason_Secondary__c) need to be required just like Order Line (Order_Line__c) is. I was able to add the asterisks in the code but I cannot get it to error on null. Here is the screen:
User-added image
When you leave Order Line blank, here is the error:
User-added imageI need this to happen when Primary Reason and Secondary Reason are left blank as well. After looking through all of the code, I found the component screen and added the highlighted text to show the asterisks on the two fields:
User-added imageThe only other thing I could find was in the Helper, I believe this is where the error message comes from for the Null Order Line:
} else if(state === "ERROR"){
                var errors = action.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        //alert(errors[0].message);
                        var toastEvent = $A.get("e.force:showToast");
                        toastEvent.setParams({
                            title : 'Error',
                            message:'There is an error '+errors[0].message+'',
                            mode: 'sticky',
                            key: 'info_alt',
                            type: 'error'
                        });
                        toastEvent.fire();

But what I cannot find is the middle piece here. Where would it state in the code that IF Order Line is null - Display this error? Full Component in comments.
Thank you very much!!!!


 
Best Answer chosen by Abby Stocker
Maharajan CMaharajan C
Hi Abby,

You can add the below if condition check for these two fields validations in saveFiles method:

I don't know how orderline field validation is working but it's looks like the error is thrown from apex class. So I have added orderline null check also in below if logic.
 
saveFiles :function(cmp,event,helper){
        var action = cmp.get("c.insertCasesFile");
        /*console.log("======"+cmp.find("fileName").get("v.value"));
        console.log("===caseId==="+cmp.get("v.caseId"));
        console.log("===caseId==="+cmp.get("v.caseNumber"));
         console.log("===fileImgSource==="+cmp.find("fileImgSource").get("v.value"));
        console.log("===fileRetReason==="+cmp.find("fileRetReason").get("v.value"));
         console.log("===cmp==="+cmp.find("lookup"));
         console.log("===lookup==="+cmp.find("lookup").get("v.value"));
        console.log("===fileSecReason==="+cmp.find("fileSecReason").get("v.value"));*/
        var retReason = cmp.find("fileRetReason").get("v.value");
        var secReason = cmp.find("fileSecReason").get("v.value");
        var orderline = cmp.find("lookup").get("v.value");
        if(retReason == null || secReason == null || orderline == null){
            var toastEvent = $A.get("e.force:showToast");
            toastEvent.setParams({
                title : 'Error',
                message:'Please fill all the required fields',
                mode: 'sticky',
                key: 'info_alt',
                type: 'error'
            });
            toastEvent.fire();
        }
        else{
            action.setParams({
                fileName : cmp.find("fileName").get("v.value"),
                caseId : cmp.get("v.caseId"),
                caseNumber : cmp.get("v.caseNumber"),
                fileImgSource : cmp.find("fileImgSource").get("v.value"),
                orderLine : cmp.find("lookup").get("v.value"),
                fileRetReason : cmp.find("fileRetReason").get("v.value"),
                fileProduct : cmp.find("fileProduct").get("v.value"),
                fileSecReason : cmp.find("fileSecReason").get("v.value"),
                fileDescription : cmp.find("fileDescription").get("v.value"),
                lstContentDoc : cmp.get("v.selectedFiles"),
            });
            action.setCallback(this, function(response) {
                var state = response.getState();
                var responseValue = response.getReturnValue();
                if(state === "SUCCESS") {
                    if(responseValue == "SUCCESS") {
                        this.showToast(cmp, "success", "Success', Image succesfully tagged");
                        var closeCaseFileForm = cmp.get('v.closeCaseFileForm');
                        $A.enqueueAction(closeCaseFileForm);
                    } else {
                        console.log('====error=>');
                        this.showNotification(cmp, "error", "Something went wrong", responseValue);
                    }
                } else if(state === "ERROR"){
                    var errors = action.getError();
                    if (errors) {
                        if (errors[0] && errors[0].message) {
                            //alert(errors[0].message);
                            var toastEvent = $A.get("e.force:showToast");
                            toastEvent.setParams({
                                title : 'Error',
                                message:'There is an error '+errors[0].message+'',
                                mode: 'sticky',
                                key: 'info_alt',
                                type: 'error'
                            });
                            toastEvent.fire();
                        }
                    }
                }else if (status === "INCOMPLETE") {
                    alert('No response from server or client is offline.');
                    var toastEvent = $A.get("e.force:showToast");
                    toastEvent.setParams({
                        title : 'Error',
                        message:'No response from server or client is offline.',
                        duration:' 5000',
                        key: 'info_alt',
                        type: 'error',
                        mode: 'pester'
                    });
                    toastEvent.fire();
                }
                cmp.set("v.disabled", false);
            });
            $A.enqueueAction(action);
        }
    }


Thanks,
Maharajan.C

All Answers

Abby StockerAbby Stocker
aura:component controller="CaseFileFormServerController">
    <!-- Attributes -->
    <aura:attribute name="disabled" type="Boolean" default="false" />
    <aura:attribute name="saved" type="Boolean" default="false" />
    <aura:attribute name="showSpinner" type="Boolean" default="false" />
    <aura:attribute name="recordId" type="String" />
    <aura:attribute name="caseId" type="String" />
    <aura:attribute name="case" type="Object" />
    <aura:attribute name="caseNumber" type="String" />
    <!-- added currentCase attribute on 09 Oct 2020 -->
    <aura:attribute name="currentCase" type="Object" />
    <!-- added closeCaseFileForm attribute on 13 Nov 2020 -->
    <aura:attribute name="closeCaseFileForm" type="Aura.Action" />
    <aura:attribute name="selectedFile" type="ContentDocument" />
    <aura:attribute name="selectedFiles" type="ContentDocument[]" />
    <aura:attribute name="casefile" type="Case_File__c"  default="{ 'sobjectType': 'Case_File__c' }"/>
    <aura:attribute name="selectedFileId" type="String" />
    <aura:attribute name="selectedFileName" type="String" />
    <!-- Handlers -->
    <aura:handler event="c:FileWasSelected" action="{!c.setSelectedFile}"/>
    <lightning:notificationsLibrary aura:id="notifications"/>
    <aura:if isTrue="{!v.showSpinner}">
        <lightning:spinner />
    </aura:if>
    <aura:if isTrue="{!!v.saved}">
        <lightning:recordEditForm aura:id="new-case-file-form"
                                  onsubmit="{!c.handleSubmit}"
                                  onsuccess="{!c.handleSuccess}"
                                  onerror="{!c.handleOnError}"
                                  objectApiName="Case_File__c">
            <lightning:messages />
            <lightning:layout multipleRows="true">
                <lightning:layoutItem size="6">
                    <lightning:inputField fieldName="Name" value="{!v.case.Subject}" aura:id="fileName" disabled="true"/>
                </lightning:layoutItem>
                <lightning:layoutItem size="6">
                    <lightning:inputField fieldName="Case__c" value="{!v.caseId}" class="disabled-lookup" aura:id="fileCase"/>
                </lightning:layoutItem>
                <lightning:layoutItem size="6">
                    <lightning:inputField fieldName="Image_Source__c" aura:id="fileImgSource"/>
                </lightning:layoutItem>
                <lightning:layoutItem size="6">
                     <lightning:inputField required="true"  fieldName="Order_Line__c" aura:id="lookup" value="" />
                </lightning:layoutItem>
                <lightning:layoutItem size="6">
                    <lightning:inputField required="true" fieldName="Return_Reason__c" aura:id="fileRetReason"/>
                </lightning:layoutItem>
                <lightning:layoutItem size="6">
                    <lightning:inputField fieldName="Product__c" aura:id="fileProduct"/>
                </lightning:layoutItem>
                <lightning:layoutItem size="6">
                    <lightning:inputField required="true" fieldName="Return_Reason_Secondary__c" aura:id="fileSecReason"/>
                </lightning:layoutItem>        
                <lightning:layoutItem size="12">
                    <lightning:inputField fieldName="Description__c" aura:id="fileDescription"/>
                </lightning:layoutItem>

            </lightning:layout>
            
            <div class="slds-m-top_medium" align="right">
                <lightning:button label="Cancel" title="Cancel" onclick="{! v.closeCaseFileForm }"/>
                <lightning:button disabled="{!v.disabled}" variant="brand"  label="Save" onclick="{!c.handleSubmit1}" />
            </div>
        </lightning:recordEditForm>
        <!--lightning:messages />
        <lightning:layout multipleRows="true">
            <lightning:layoutItem size="6">
                Order Line
                <force:inputField aura:id="firstname" value="{!v.casefile.Order_Line__c}"/>
            </lightning:layoutItem>
            <lightning:layoutItem size="6">
            </lightning:layoutItem>
            <lightning:layoutItem size="6">
            </lightning:layoutItem>
            <lightning:layoutItem size="6">
            </lightning:layoutItem>
            <lightning:layoutItem size="6">
            </lightning:layoutItem>
            <lightning:layoutItem size="6">
            </lightning:layoutItem>
            <lightning:layoutItem size="6">
            </lightning:layoutItem>
            
            <lightning:layoutItem size="12">
            </lightning:layoutItem>
            
        </lightning:layout>
        
        <div class="slds-m-top_medium" align="right">
            <lightning:button label="Cancel" title="Cancel" onclick="{! v.closeCaseFileForm }"/>
            <lightning:button disabled="{!v.disabled}" variant="brand"  label="Save" />
        </div-->
        <aura:set attribute="else">
            <p>Saved! New record id is {!v.recordId}</p>
        </aura:set>
    </aura:if>
</aura:component>
Helper:
({
    linkFile : function(cmp, documentId, caseFileId) {
        var linkFileAction = cmp.get("c.linkFileToCaseFile");
        linkFileAction.setParams({
            fileId : documentId,
            caseId : caseFileId
        });
        linkFileAction.setCallback(this, function(response) {
            var state = response.getState();
            var responseValue = response.getReturnValue();
            if(state === "SUCCESS") {
                if(responseValue == "SUCCESS") {
                    this.showToast(cmp, "success", "Success', Image succesfully tagged");
                } else {
                    this.showNotification(cmp, "error", "Something went wrong", responseValue);
                }
            } else {
                this.showNotification(cmp, "error", "Something went wrong", "Unexpected exception occurred");
            }
            cmp.set("v.disabled", false);
        });
        $A.enqueueAction(linkFileAction);
    },
    
    showToast : function(cmp, variant, title, message) {
        cmp.find('notifications').showToast({
            "variant" : variant,
            "title": title,
            "message": message
        });
    },
    
    showNotification : function(cmp, variant, header, message) {
        cmp.find('notifications').showNotice({
            "variant": variant,
            "header": header,
            "message": message,
            closeCallback: function() {}
        });
    },
    
    refreshScreen : function(cmp) {
        window.setTimeout(
            $A.getCallback(function () {
                $A.get('e.force:refreshView').fire();
            }), 3000
        );
    },
    saveFiles :function(cmp,event,helper){
        var action = cmp.get("c.insertCasesFile");
        /*console.log("======"+cmp.find("fileName").get("v.value"));
        console.log("===caseId==="+cmp.get("v.caseId"));
        console.log("===caseId==="+cmp.get("v.caseNumber"));
         console.log("===fileImgSource==="+cmp.find("fileImgSource").get("v.value"));
        console.log("===fileRetReason==="+cmp.find("fileRetReason").get("v.value"));
         console.log("===cmp==="+cmp.find("lookup"));
         console.log("===lookup==="+cmp.find("lookup").get("v.value"));
        console.log("===fileSecReason==="+cmp.find("fileSecReason").get("v.value"));*/
        action.setParams({
            fileName : cmp.find("fileName").get("v.value"),
            caseId : cmp.get("v.caseId"),
            caseNumber : cmp.get("v.caseNumber"),
            fileImgSource : cmp.find("fileImgSource").get("v.value"),
            orderLine : cmp.find("lookup").get("v.value"),
            fileRetReason : cmp.find("fileRetReason").get("v.value"),
            fileProduct : cmp.find("fileProduct").get("v.value"),
            fileSecReason : cmp.find("fileSecReason").get("v.value"),
            fileDescription : cmp.find("fileDescription").get("v.value"),
            lstContentDoc : cmp.get("v.selectedFiles"),
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            var responseValue = response.getReturnValue();
            if(state === "SUCCESS") {
                if(responseValue == "SUCCESS") {
                    this.showToast(cmp, "success", "Success', Image succesfully tagged");
                    var closeCaseFileForm = cmp.get('v.closeCaseFileForm');
        			$A.enqueueAction(closeCaseFileForm);
                } else {
                    console.log('====error=>');
                    this.showNotification(cmp, "error", "Something went wrong", responseValue);
                }
            } else if(state === "ERROR"){
                var errors = action.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        //alert(errors[0].message);
                        var toastEvent = $A.get("e.force:showToast");
                        toastEvent.setParams({
                            title : 'Error',
                            message:'There is an error '+errors[0].message+'',
                            mode: 'sticky',
                            key: 'info_alt',
                            type: 'error'
                        });
                        toastEvent.fire();
                    }
                }
            }else if (status === "INCOMPLETE") {
                alert('No response from server or client is offline.');
                var toastEvent = $A.get("e.force:showToast");
                        toastEvent.setParams({
                            title : 'Error',
                            message:'No response from server or client is offline.',
                            duration:' 5000',
                            key: 'info_alt',
                            type: 'error',
                            mode: 'pester'
                        });
                        toastEvent.fire();
            }
            cmp.set("v.disabled", false);
        });
        $A.enqueueAction(action);
    }
})


 
Maharajan CMaharajan C
Hi Abby,

You can add the below if condition check for these two fields validations in saveFiles method:

I don't know how orderline field validation is working but it's looks like the error is thrown from apex class. So I have added orderline null check also in below if logic.
 
saveFiles :function(cmp,event,helper){
        var action = cmp.get("c.insertCasesFile");
        /*console.log("======"+cmp.find("fileName").get("v.value"));
        console.log("===caseId==="+cmp.get("v.caseId"));
        console.log("===caseId==="+cmp.get("v.caseNumber"));
         console.log("===fileImgSource==="+cmp.find("fileImgSource").get("v.value"));
        console.log("===fileRetReason==="+cmp.find("fileRetReason").get("v.value"));
         console.log("===cmp==="+cmp.find("lookup"));
         console.log("===lookup==="+cmp.find("lookup").get("v.value"));
        console.log("===fileSecReason==="+cmp.find("fileSecReason").get("v.value"));*/
        var retReason = cmp.find("fileRetReason").get("v.value");
        var secReason = cmp.find("fileSecReason").get("v.value");
        var orderline = cmp.find("lookup").get("v.value");
        if(retReason == null || secReason == null || orderline == null){
            var toastEvent = $A.get("e.force:showToast");
            toastEvent.setParams({
                title : 'Error',
                message:'Please fill all the required fields',
                mode: 'sticky',
                key: 'info_alt',
                type: 'error'
            });
            toastEvent.fire();
        }
        else{
            action.setParams({
                fileName : cmp.find("fileName").get("v.value"),
                caseId : cmp.get("v.caseId"),
                caseNumber : cmp.get("v.caseNumber"),
                fileImgSource : cmp.find("fileImgSource").get("v.value"),
                orderLine : cmp.find("lookup").get("v.value"),
                fileRetReason : cmp.find("fileRetReason").get("v.value"),
                fileProduct : cmp.find("fileProduct").get("v.value"),
                fileSecReason : cmp.find("fileSecReason").get("v.value"),
                fileDescription : cmp.find("fileDescription").get("v.value"),
                lstContentDoc : cmp.get("v.selectedFiles"),
            });
            action.setCallback(this, function(response) {
                var state = response.getState();
                var responseValue = response.getReturnValue();
                if(state === "SUCCESS") {
                    if(responseValue == "SUCCESS") {
                        this.showToast(cmp, "success", "Success', Image succesfully tagged");
                        var closeCaseFileForm = cmp.get('v.closeCaseFileForm');
                        $A.enqueueAction(closeCaseFileForm);
                    } else {
                        console.log('====error=>');
                        this.showNotification(cmp, "error", "Something went wrong", responseValue);
                    }
                } else if(state === "ERROR"){
                    var errors = action.getError();
                    if (errors) {
                        if (errors[0] && errors[0].message) {
                            //alert(errors[0].message);
                            var toastEvent = $A.get("e.force:showToast");
                            toastEvent.setParams({
                                title : 'Error',
                                message:'There is an error '+errors[0].message+'',
                                mode: 'sticky',
                                key: 'info_alt',
                                type: 'error'
                            });
                            toastEvent.fire();
                        }
                    }
                }else if (status === "INCOMPLETE") {
                    alert('No response from server or client is offline.');
                    var toastEvent = $A.get("e.force:showToast");
                    toastEvent.setParams({
                        title : 'Error',
                        message:'No response from server or client is offline.',
                        duration:' 5000',
                        key: 'info_alt',
                        type: 'error',
                        mode: 'pester'
                    });
                    toastEvent.fire();
                }
                cmp.set("v.disabled", false);
            });
            $A.enqueueAction(action);
        }
    }


Thanks,
Maharajan.C
This was selected as the best answer
Felipe PintoFelipe Pinto
thank you lots