+ Start a Discussion
Ash asmanAsh asman 

Hi all please help me how write alert messages for this ligthning component?

Hi all I created new lead Record using Ligthning component Iam getting the record in salesforce org using visual force now iam facing the error .That  was i want show alert messages when click to submit a record and if any fileds are empty show message please fill the empty fileds.
please help me how to write the alert messages show to end user .
this is my component.
<aura:component  access="global"  controller="createleadscls"  implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" >
    
    <ltng:require styles="/resource/SLDS0122/assets/styles/salesforce-lightning-design-system.min.css"/>
    <!--aura:handler name="init" value="{!this}" action="{!c.onInit}"/-->
    
    <aura:registerEvent name="check" type="c:lightingleadevent"/>
    <aura:attribute name="newLead" type="Lead"
                    default="{ 'sobjectType': 'Lead',
                             'FirstName' : '',
                             'LastName' : '',
                             'Company': '',
                             'Phone' : '',
                             'Email':'',
                             'Title' :'' ,
                             }"/>
   
    

      <div>
         <!--c:util aura:id="theUtil" title="Search Options" /-->    
    </div>
    <fieldset class="slds-box slds-theme--default slds-container--small">
        <legend id="leadform" class="slds-text-heading--smallslds-p-vertical--medium">
            lead Form
        </legend>
      
        
        <div>
            <lightning:input aura:id="leadid" label="First Name"
                             class="slds-input"
                             labelClass="slds-form-element__label"
                             value="{!v.newLead.FirstName}"
                             />
        </div>
        
      
      
        <br/>    
        <div>
            <lightning:input aura:id="leadid" label="Last Name"
                             class="slds-input"
                             labelClass="slds-form-element__label"
                             value="{!v.newLead.LastName}"
                             />
        </div>
        
        <br/>
        <div>  
            <lightning:input aura:id="leadid" label="Company"
                             class="slds-input"
                             labelClass="slds-form-element__label"
                             value="{!v.newLead.Company}"
                             />
        </div>
     
        <br/>
        <div>
            <lightning:input aura:id="leadid" label="Phone"
                             class="slds-input"
                             labelClass="slds-form-element__label"
                             value="{!v.newLead.Phone}" maxlength="12"
                             pattern="^(\s*\d\s*){12}$"
                             messageWhenPatternMismatch="Phone number is not valid/enter with country code also"
                             required="true" />
        </div>
       
        <br/>
        <div>
            <lightning:input aura:id="leadid" label="Email"
                             class="slds-input"
                             labelClass="slds-form-element__label"
                             value="{!v.newLead.Email}"
                             pattern="^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"
                             
                             messageWhenPatternMismatch="Please enter a valid Email Address"
                             required="true" />
            <!-- /\s+@\s+\.\s+/" -->
            
            
        </div>
        
        <br/>
        <div>
            <lightning:input aura:id="leadid" label="Title"
                             class="slds-input"
                             labelClass="slds-form-element__label"
                             value="{!v.newLead.Title}"
                             required="false"
                             />
        </div>
       
       
        <br/>
   
        <lightning:button aura:id="leadclk" variant="brand" label="Create"
                          onclick="{!c.createleadclick}"/>
       
       
    </fieldset>
    
</aura:component>

controller :
({
     createleadclick : function(component, event, helper) {
        helper.createclick(component);
    },
    
})
helper:
({
    createclick : function(component) {
        alert("button clicked");
        //Getting the lead from page
        var newlec = component.get("v.newLead");
        console.log(newlec);
        
        //Assign server method to action variable
        var action = component.get("c.saveLead");
        //setting parameters for server method
        action.setParams({
            "ledrec": newlec
        });
        action.setCallback(this, function(response) {
            //Getting the response state
            var state = response.getState();
            
            //check if response is success
            console.log(state);
            
            if (state === "SUCCESS") {
              var state= response.getReturnValue();
                component.set("v.newLead",response.getReturnvalue());
                this.showMessage(component,'created successfully','success');
                console.log(component);
               //  alert('Record is Created Successfully');
            } else if(state === "ERROR"){
                alert("error");
               this.showMessage(component,response.getError());
            }
        });
        $A.enqueueAction(action);
        //  var resultToast =$A.get("e.force:showToast");
        
        
        /*if (state === "SUCCESS") {
                resultToast.setParams({
                    "title": "Success!",
                    "message": "The record has been updated successfully."
                });
            }*/
        /*  else if(state=="ERROR"){
                var errors=response.getError();
                console.log(errors);
                if(errors){
                    if(errors[0]&& errors[0].message){
                        resultToast.setParams({"title":"Update Error",
                                               "message":"The update validation returned an error:"
                                              });
                    }
                }
            }else{
                resultsToast.setParams({
                    "title":"Update unknown Error",
                    "message": "The update returnde an error:" +state
                });
            }*/
        //resultToast.fire();
        /*$A.get("e.force:refreshView").fire();
            
            //This closes the Action Window
            var dismissActionPanel=$A.get("e.force:closeQuickAction");
            dismissActionPanel.fire();*/
        
        
        
        
    },  
   /* createleadclick : function(component) {
        if(this.cisclick(component)){
            var theEvent = component.getEvent("check");
            theEvent.setParams({"newlec":component.get("v.newLead")
                  
            }).fire();
        }else{
            this.showMessage(component,'complete all text fileds','error');
        }
    },*/
    showMessage: function(component,message,messageType){
        component.find("theUtil").showMessage(message, messageType);
    },     
    showErrors: function(component,message){
        component.find("theUtil").showErrors(message);
    },
    showLog: function(component,message){
        component.find("theUtil").log(message);
    },    
    
    // Adding the action variable to the global action queue
    // $A.enqueueAction(action)
    
    /* handleCancel: function (cmp, event, helper) {
     
    var toastEvent = $A.get("e.force:showToast");
    toastEvent.setParams({
        "title": "Success!",
        "message": "The record has been updated successfully."
    });
    toastEvent.fire();

        cmp.set("v.newLead", false);
    }*/
})

vf page:
<apex:page showHeader="false" standardStylesheets="false" standardController="Lead">
    <apex:form >
        <!--apex:image url="{!$Resource.NewLogo}" style="width:150px;height:150px;padding:9px;float:center;"
            rendered="true" /-->
        <!--apex:stylesheet value="{!URLFOR($Resource.newjquery, 'css/themes/default/jquery.mobile-1.2.1.css')}"
        /-->
        <apex:includeLightning />


        <div style="width:50%;height:50px;" id="lexContainer">
            <div style="height:5rem;" id="sliderDemo">
                <br/>
                <div role="status" class="slds-spinner slds-spinner_medium">
                    <span class="slds-assistive-text">Loading</span>
                    <div class="slds-spinner__dot-a"></div>
                    <div class="slds-spinner__dot-b"></div>
                </div>
            </div>
        </div>

        <script>
            $Lightning.use("c:lightingleadapp", function() {
                $Lightning.createComponent("c:createleaddata", {},
                    "lexContainer",
                    function(cmp) {
                        document.getElementById("sliderDemo").style
                            .display = 'none';
                    });
            });

        </script>
    </apex:form>

</apex:page>

Apex Class:
public class createleadscls {
 
    @AuraEnabled
 public  static Lead  saveLead (Lead ledrec) {
       upsert ledrec;
     return ledrec;
          
           }
}
 Ligthning application:
<!--aura:application access="GLOBAL"  
                    implements="ltng:allowGuestAccess"-->
<aura:application access="GLOBAL" extends="ltng:outApp" >
    
    
    <aura:dependency resource="c:createleaddata"/>
    <c:createleaddata />
</aura:application>



 
Khan AnasKhan Anas (Salesforce Developers) 
Hi Ash,

Greetings to you!

You can use messageWhenValueMissing on lightning:input to display the error message when the value is missing. Please refer to the below links which might help you further with the above requirement.

https://developer.salesforce.com/docs/component-library/bundle/lightning:input/specification

http://salesforcehelpblog.blogspot.com/2017/10/working-with-custom-validations-using.html

https://salesforce.stackexchange.com/questions/181094/how-to-validate-all-form-fields-on-click-of-button-using-showhelpmessageifinvali

https://developer.salesforce.com/forums/?id=9060G0000005q1qQAA

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas