How to Insert New Record with Radio Button, Checkbox, Datepicker, Picklist, Long Text Area Using Lightning Component and Apex Controller | how to submit form Value in lightning component in Salesforce

1,921 views

Hey guys, today in this post we are going to learn about how to Insert New Record with Radio Button, Checkbox, Date picker, Picklist, Long Text Area Using Lightning Component and Apex Controller.

We used the files in this example:-

submitFormCustomObjApp.app Lightning Application It is used for call the component to preview on browser.

submitFormCustomObjCmp.cmp

Lightning Component It is used for create a custom form on lightning component .

submitFormCustomObjCmpController.js

JavaScript Controller File It is used for click function for insert a form input value in database.
submitFormCustomObjCmpHelper.js JavaScript Controller HelperFile It is used for fatch the picklist value from server of State and City
submitFormCustomObjCmp.css Component Style CSS It is used for create custom Style CSS for alignment the form input field and section.
submitFormCustomObjCmpCtrl.apxc Apex Class Controller It is used for insert input value into database server

Live Demo

insert new record using lightning component -- w3web.net

 

 

You can download file directly from github by Click Here.

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!

 

 

 

Other related post that would you like to learn in Salesforce

 

Step 1:- Create Lightning Application : submitFormCustomObjApp.app

From Developer Console >> File >> New >> Lightning Application

submitFormCustomObjApp.app [Component Application File]

  1.   <aura:application extends="force:slds">
  2.     <c:submitFormCustomObjCmp/>
  3. </aura:application>

Step 2:- Create Lightning Component : submitFormCustomObjCmp.cmp

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 

From Developer Console >> File >> New >> Lightning Component

submitFormCustomObjCmp.cmp [Lightning Component File]

  1.    <aura:component controller="submitFormCustomObjCmpCtrl" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >	
  2.     <aura:attribute name="newStudent" type="NewStudent__c" default="{'sobjectType' : 'NewStudent__c'}"/>
  3.     <aura:attribute name="cityListStr" type="string[]" />    
  4.     <aura:attribute name="stateListStr" type="string[]" />        
  5.     <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
  6.  
  7.     <div class="slds">       
  8.         <div class="slds-grid slds-wrap">
  9.             <div class="slds-col--padded-large slds-large-size--6-of-12 slds-medium-size--6-of-12 slds-small-size--12-of-12 slds-x-small-size--12-of-12 slds-m-top--small">
  10.                 <div class="slds-form-element slds-is-required">
  11.                     <label class="slds-form-element__label">Student Name</label>
  12.                     <ui:inputText class="slds-input" aura:id="studentName" value="{!v.newStudent.Name}"/>
  13.                 </div>
  14.             </div> 
  15.  
  16.             <div class="slds-col--padded-large slds-large-size--6-of-12 slds-medium-size--6-of-12 slds-small-size--12-of-12 slds-x-small-size--12-of-12 slds-m-top--small">
  17.                 <div class="slds-form-element slds-is-required">
  18.                     <label class="slds-form-element__label">Email</label>
  19.                     <ui:inputEmail class="slds-input" aura:id="emailId" value="{!v.newStudent.Email__c}"/>
  20.                 </div>
  21.             </div> 
  22.  
  23.  
  24.          <div class="slds-col--padded-large slds-large-size--6-of-12 slds-medium-size--6-of-12 slds-small-size--12-of-12 slds-x-small-size--12-of-12 slds-m-top--small">
  25.                 <div class="slds-form-element slds-is-required">
  26.                     <label class="slds-form-element__label">State</label>
  27.                     <div class="slds-form-element__controller">
  28.                        <ui:inputSelect class="slds-select" aura:id="stateName" change="{!c.changeStateName}" value="{!v.newStudent.State__c}">
  29.                            <ui:inputSelectOption text="--None--" />
  30.                            <aura:iteration items="{!v.stateListStr}" var="stateVal">
  31.                                <ui:inputSelectOption text="{!stateVal}" />
  32.                            </aura:iteration>          
  33.                        </ui:inputSelect>
  34.                     </div>
  35.  
  36.                 </div>
  37.             </div>
  38.  
  39.  
  40.             <div class="slds-col--padded-large slds-large-size--6-of-12 slds-medium-size--6-of-12 slds-small-size--12-of-12 slds-x-small-size--12-of-12 slds-m-top--small">
  41.                 <div aura:id="idSearchboxProductionExecutives" class="slds-form-element slds-is-required">
  42.                     <label class="slds-form-element__label">City</label>
  43.                     <div class="slds-form-element__controller">
  44.                        <ui:inputSelect class="slds-select" aura:id="cityName" change="{!c.changeCityName}" value="{!v.newStudent.City__c}">
  45.                                 <ui:inputSelectOption text="--None--" />
  46.                                  <aura:iteration items="{!v.cityListStr}" var="cityVal">
  47.                                      <ui:inputSelectOption text="{!cityVal}" />
  48.                                  </aura:iteration>          
  49.                             </ui:inputSelect>
  50.                     </div>
  51.  
  52.                 </div>
  53.             </div>
  54.  
  55.             <div class="slds-col--padded-large slds-large-size--6-of-12 slds-medium-size--6-of-12 slds-small-size--12-of-12 slds-x-small-size--12-of-12 slds-m-top--small">
  56.                 <div class="slds-form-element slds-is-required">
  57.                     <div class="slds-form-element__controller">
  58.                         <lightning:input type="date" name="dateOfBirth" aura:id="dateOfBirth" value="{!v.newStudent.DateOfBirth__c}"  label="Date Of Birth" labelClass="slds-form-element__label"/>
  59.                     </div>
  60.  
  61.                 </div>
  62.             </div>
  63.  
  64.             <div class="slds-col--padded-large slds-large-size--6-of-12 slds-medium-size--6-of-12 slds-small-size--12-of-12 slds-x-small-size--12-of-12 slds-m-top--small">
  65.                 <div class="slds-form-element slds-is-required">
  66.                     <label class="slds-form-element__label">Gender</label>
  67.                     <div class="slds-form-element__controller">
  68.                        <div class="slds-grid slds-wrap slds-m-bottom--small">
  69.  
  70.                        <label class="slds-radio">
  71.                             <input type="radio" id="maleOption"  class="slds-m-right--medium" name="options" value="Male"  checked="{!equals(v.newStudent.Gender__c,'Male')}" onclick="{!c.setGenderValue}"/> 
  72.                             <span class="slds-radio--faux"></span>
  73.                             <span class="slds-form-element__label"> Male</span>
  74.                         </label>
  75.  
  76.                       <label class="slds-radio">
  77.                           <input type="radio" id="femaleOption"  name="options" value="Female" checked="{!equals(v.newStudent.Gender__c,'Female')}" onclick="{!c.setGenderValue}"/> 
  78.                           <span class="slds-radio--faux"></span>
  79.                           <span class="slds-form-element__label"> Female</span>
  80.                       </label>
  81.  
  82.                    </div>
  83.                     </div>
  84.  
  85.                 </div>
  86.             </div>
  87.  
  88.             <div class="slds-col--padded-large slds-large-size--6-of-12 slds-medium-size--6-of-12 slds-small-size--12-of-12 slds-x-small-size--12-of-12 slds-m-top--small">
  89.                 <div class="slds-form-element slds-is-required">
  90.                     <label class="slds-form-element__label">Is Married?</label>
  91.                     <div class="slds-form-element__controller">                        
  92.                        <lightning:input type="checkbox" aura:id="checkbox" name="IsMarried" onchange="{!c.onCheck}"/>                        
  93.                     </div>
  94.                 </div>
  95.                 <aura:if isTrue="{!v.newStudent.IsMarried__c}">
  96.                 <div  class="slds-form-element slds-is-required slds-m-top--small">
  97.                     <label class="slds-form-element__label">Spouse Name</label>
  98.                     <ui:inputText class="slds-input" aura:id="spouseName" value="{!v.newStudent.SpouseName__c}" />
  99.                 </div>
  100.               </aura:if>
  101.  
  102.  
  103.  
  104.             </div>
  105.             <div class="slds-col--padded-large slds-large-size--6-of-12 slds-medium-size--6-of-12 slds-small-size--12-of-12 slds-x-small-size--12-of-12 slds-m-top--small">
  106.  
  107.                 <div  class="slds-form-element slds-is-required">
  108.                     <label class="slds-form-element__label">Address</label>
  109.                     <ui:inputTextArea aura:id="address" class="slds-textarea" value="{!v.newStudent.Address__c}" rows="2"/>
  110.                 </div>
  111.             </div>
  112.  
  113.  
  114.         </div>
  115.  
  116.         <div class="slds-text-align--center slds-m-top--medium slds-m-bottom--medium">
  117.             <button class="slds-button slds-button--brand" onclick="{!c.submitAction}">Submit</button>
  118.         </div>
  119.         <br/>
  120.  
  121. <br/> <br/>
  122.    <!--Start RelatedTopics Section-->
  123. <div style="border:1px #ddd solid; padding:10px; background:#eee; margin:40px 0;">
  124.  
  125.             <p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/05/thumbsUpLike.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:16px; font-style:italic; display:inline-block; margin-right:5px;">Don't forget to check out:-</span><a href="https://www.w3web.net/" target="_blank" rel="noopener noreferrer" style="text-decoration:none;" data-aura-rendered-by="440:0">An easy way to learn step-by-step online free Salesforce tutorial, To know more Click  <span style="color:#ff8000; font-size:18px;" data-aura-rendered-by="442:0">Here..</span></a></strong></p>
  126.  
  127.             <br/><br/>
  128.             <p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/07/tickMarkIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:17px; font-style:italic; display:inline-block; margin-right:5px; color:rgb(255 128 0);">You May Also Like →</span> </strong></p>
  129.             <div style="display:block; overflow:hidden;"> 
  130.                 <div style="width: 50%; float:left; display:inline-block">
  131.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  132.                         <li><a href="https://www.w3web.net/lwc-get-set-lightning-checkbox-value/" target="_blank" rel="noopener noreferrer">How to get selected checkbox value in lwc</a></li>
  133.                         <li><a href="https://www.w3web.net/display-account-related-contacts-in-lwc/" target="_blank" rel="noopener noreferrer">how to display account related contacts based on AccountId in lwc</a></li>
  134.                         <li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to create lightning datatable row actions in lwc</a></li>
  135.                         <li><a href="https://www.w3web.net/if-and-else-condition-in-lwc/" target="_blank" rel="noopener noreferrer">how to use if and else condition in lwc</a></li>
  136.                         <li><a href="https://www.w3web.net/get-selected-radio-button-value-and-checked-default-in-lwc/" target="_blank" rel="noopener noreferrer">how to display selected radio button value in lwc</a></li>
  137.                     </ul>
  138.             </div>
  139.  
  140.             <div style="width: 50%; float:left; display:inline-block">
  141.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  142.                         <li><a href="https://www.w3web.net/display-account-related-contacts-lwc/" target="_blank" rel="noopener noreferrer">display account related contacts based on account name in lwc</a></li>
  143.                         <li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to insert a record of account Using apex class in LWC</a></li>
  144.                         <li><a href="https://www.w3web.net/fetch-picklist-values-dynamic-in-lwc/" target="_blank" rel="noopener noreferrer">how to get picklist values dynamically in lwc</a></li>
  145.                         <li><a href="https://www.w3web.net/edit-save-and-remove-rows-dynamically-in-lightning-component/" target="_blank" rel="noopener noreferrer">how to edit/save row dynamically in lightning component</a></li>
  146.                         <li><a href="https://www.w3web.net/update-parent-object-from-child/" target="_blank" rel="noopener noreferrer">update parent field from child using apex trigger</a></li>
  147.                     </ul>
  148.                 </div>
  149.                <div style="clear:both;"></div> 
  150.                <br/>
  151.                 <div class="youtubeIcon">
  152.                     <a href="https://www.youtube.com/channel/UCW62gTen2zniILj9xE6LmOg" target="_blank" rel="noopener noreferrer"><img src="https://www.w3web.net/wp-content/uploads/2021/11/youtubeIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;"/> <strong>TechW3web:-</strong> To know more, Use this <span style="color: #ff8000; font-weight: bold;">Link</span> </a>
  153.                 </div>
  154.     </div>
  155.  
  156. </div>
  157.  
  158.   <!--End RelatedTopics Section-->
  159.  
  160.     </div>  
  161. </aura:component>

Step 3:- Create Lightning Component : submitFormCustomObjCmpController.js

From Developer Console >> File >> New >> Lightning Component >> JavaScript Controller

submitFormCustomObjCmpController.js [JavaScript Controller]

  1.   ({
  2.  
  3.     doInit:function(component, event, helper){
  4.         helper.cityPickListView(component);
  5.         helper.statePickListView(component);        
  6.     },
  7.  
  8.  
  9.     submitAction : function(component, event, helper) {
  10.         var action = component.get("c.newStudentMethod");
  11.         var newStudent = component.get('v.newStudent');
  12.         var checkbox = component.find('checkbox').get('v.checked');
  13.         var validate = true;
  14.         var studentName = component.find('studentName');
  15.         var studentNameVal = component.find('studentName').get('v.value');
  16.         var emailVal = component.get('v.newStudent.Email__c');        
  17.  
  18.  
  19.         if($A.util.isUndefinedOrNull(studentNameVal) || $A.util.isUndefined(studentNameVal) || $A.util.isEmpty(studentNameVal)){
  20.             studentName.set("v.errors",[{message:"Please select required field"}]);
  21.             validate = false; 
  22.         }else{
  23.             studentName.set("v.errors",null);
  24.         }
  25.  
  26.         if(validate){
  27.             action.setParams({"studentRecId":newStudent});  
  28.  
  29.             action.setCallback(this, function(response){
  30.                 var state = response.getState();                       
  31.                 if(state == "SUCCESS"){
  32.                     var result = response.getReturnValue();                    
  33.                     //alert('result ' + result);
  34.                         component.set('v.newStudent.Name','');
  35.                         component.set('v.newStudent.Email__c','');
  36.                         component.set('v.newStudent.State__c','--None--');
  37.                         component.set('v.newStudent.City__c','--None--');                        
  38.                         component.set('v.newStudent.DateOfBirth__c','');               
  39.                         component.set('v.newStudent.SpouseName__c','');
  40.                         component.set('v.newStudent.Address__c','');
  41.                         component.set('v.newStudent.Gender__c',null); 
  42.                         component.find('checkbox').set('v.checked',false);
  43.  
  44.                   /* 
  45.                     var toastEvent = $A.get("e.force:showToast");
  46.                         toastEvent.setParams({
  47.                             "title": "Success!",
  48.                             "type":'success',
  49.                             "message": "The record has been updated successfully."
  50.                         });
  51.                         toastEvent.fire();
  52.                     */   
  53.  
  54.                    alert('Record saved successfully');
  55.                 }
  56.             });
  57.  
  58.             $A.enqueueAction(action);
  59.         }
  60.  
  61.     },
  62.  
  63.  
  64.     changeCityName:function(component, event, helper){
  65.         var cityName = component.find('cityName').get('v.value');        
  66.         component.set('v.newStudent.City__c',cityName);
  67.     },
  68.  
  69.  
  70.     changeStateName:function(component, event, helper){
  71.         var stateName = component.find('stateName').get('v.value');
  72.         component.set('v.newStudent.State__c',stateName);
  73.     },
  74.  
  75.  
  76.     setCheckBoxValue: function(component,event) {
  77.         var val = event.currentTarget.value;
  78.  
  79.         component.set("v.newStudent.IsMarried__c",val);
  80.     },
  81.  
  82.  
  83.     onCheck: function(component,event) {
  84.         var checkbox = component.find('checkbox').get('v.checked');        
  85.         component.set("v.newStudent.IsMarried__c",checkbox);
  86.     },
  87.  
  88.     setGenderValue: function(component,event) {
  89.         var val = event.currentTarget.value;
  90.         //alert(val);
  91.         component.set("v.newStudent.Gender__c",val);
  92.     },
  93.  
  94.  
  95. })

Step 4:- Create Lightning Component : submitFormCustomObjCmpHelper.js

From Developer Console >> File >> New >> Lightning Component >> JavaScript Helper

submitFormCustomObjCmpHelper.js [JavaScript Helper File]

JavaScript helper function in Salesforce by w3web.net

  1.   ({
  2. 	cityPickListView : function(component, event, helper) {
  3. 		var action = component.get("c.pickList");
  4.         action.setParams({"obj":"NewStudent__c","str":"City__c"});        
  5.         action.setCallback(this, function(response){
  6.             var state = response.getState();            
  7.             if(state=="SUCCESS"){
  8.                 var result = response.getReturnValue();
  9.                 component.set('v.cityListStr',result);
  10.  
  11.             }
  12.         });
  13.         $A.enqueueAction(action);
  14. 	},
  15.  
  16.  
  17.     statePickListView : function(component, event, helper) {
  18. 		var action = component.get("c.pickList");
  19.         action.setParams({"obj":"NewStudent__c","str":"State__c"});        
  20.         action.setCallback(this, function(response){
  21.             var state = response.getState();            
  22.             if(state=="SUCCESS"){
  23.                 var result = response.getReturnValue();
  24.                 component.set('v.stateListStr',result);
  25.  
  26.             }
  27.         });
  28.         $A.enqueueAction(action);
  29. 	},
  30.  
  31. })

Step 5:- Create Lightning Component Style: submitFormCustomObjCmp.css

From Developer Console >> File >> New >> Lightning Component >> Component Style CSS

submitFormCustomObjCmp.css [Style CSS]

  1.    .THIS {
  2.     background:#fff !important;
  3. }
  4. .THIS .slds-input.has-error, .THIS .slds-select.has-error {
  5.     background-color: rgb(255, 255, 255);
  6.     border-color: rgb(194, 57, 52);
  7.     box-shadow: rgb(194, 57, 52) 0 0 0 1px inset;
  8.     background-clip: padding-box;
  9.   }

Step 6:- Create Apex Class : submitFormCustomObjCmpCtrl

From Developer Console >> File >> New >> Apex Class

studentInfoCtrl.apxc [Apex Class Controller]

  1.    public class submitFormCustomObjCmpCtrl {
  2.     @AuraEnabled
  3.     public static void newStudentMethod(NewStudent__c studentRecId){
  4.         upsert studentRecId;
  5.     } 
  6.  
  7.     @AuraEnabled
  8.     public static string newStudentInsrt(string nameStr, string emailStr){
  9.         NewStudent__c stdntNameStr = NEW NewStudent__c();
  10.         List<NewStudent__c> stdntNameList=[SELECT Id, Name FROM NewStudent__c WHERE Name =: nameStr]; 
  11.         IF(stdntNameList.size() > 0){
  12.             RETURN 'Duplicate name Not Allow';
  13.         }ELSE{
  14.         stdntNameStr.Name=nameStr;
  15.         stdntNameStr.Email__c=emailStr;
  16.         INSERT stdntNameStr;
  17.           RETURN 'Inserted successfully';  
  18.         }    
  19.  
  20.     }
  21.  
  22.     @AuraEnabled
  23.     public static List<String> pickList(String obj, String str) { 
  24.  
  25.          List<String> regList = NEW List<String>(); 
  26.             Schema.DescribeFieldResult plistvalues = Schema.getGlobalDescribe().get(obj).getDescribe().fields.getMap().get(str).getDescribe();
  27.             FOR(PicklistEntry ent:plistvalues.getpicklistvalues())     {
  28.                 regList.add(ent.getLabel());
  29.             }
  30.              RETURN regList;
  31.     }
  32. }

 

 

Further post that would you like to learn in Salesforce

 
 

 

 

FAQ (Frequently Asked Questions)

How do you display record details with lightning component?

To display a record using lightning:recordForm , provide the record ID and the object API name. Additionally, provide fields using either the fields or layoutType attribute. You can display a record in two modes using the mode attribute. Loads the form using output fields with inline editing enabled.

How do you add a new record with lightning component?

To create a record using force:recordData , leave out the recordId attribute. Load a record template by calling the getNewRecord function on force:recordData . Finally, apply values to the new record, and save the record by calling the saveRecord function on force:recordData

How do you show radio buttons horizontally in lightning?

Use label-inline to horizontally align the label and radio group. Use label-stacked to place the label above the radio group.

Related Topics | You May Also Like

 
Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 
  

Our Free Courses →

👉 Get Free Course →

📌 Salesforce Administrators

📌 Salesforce Lightning Flow Builder

📌 Salesforce Record Trigger Flow Builder

👉 Get Free Course →

📌 Aura Lightning Framework

📌 Lightning Web Component (LWC)

📌 Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Leave a Comment