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
Sid LightningSid Lightning 

Save button on lightning component ?

Hi,

I want to create a save button on lightning component for my object Shipping Address which is child to parent Account.

There are 6 fields in shipping address, I want those fields to get saved and displayed on the lightning component 

I am tricked about how do i save it into database and get it displayed on my screen.

Can anyone help me on this please
 
Khan AnasKhan Anas (Salesforce Developers) 
Hi Sid,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. I have used Contact object. Kindly modify the code as per your requirement.

Apex:
public class InsertAndDisplayC {
    
    @AuraEnabled
    public static Id saveDetails(Contact con){
        // DML operation to save Contact Details   
        INSERT con;
        return con.Id; 
    }
}

Component:
<aura:component controller="InsertAndDisplayC"
                implements="lightning:isUrlAddressable,force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute name="PageHeading" type="String" default="Create and Display Contacts"/>
    <aura:attribute name="RegForm" type="Contact" default="{'sobjectType' : 'Contact'}"/>
    <aura:attribute name="showDetails" type="boolean" default="false" />
    
    <div class="slds-m-top--xx-large">
        <div class="slds-page-header">
            <div class="slds-align--absolute-center">
                <div class="slds-text-heading--large">       
                    {!v.PageHeading}
                </div>
            </div>
        </div>
    </div>
    <br/> <br/>
    
    <div class = "slds-size--3-of-8">
        <lightning:input label="Enter First Name" name="fname" value="{!v.RegForm.FirstName}"/>
        <br/>
        <lightning:input label="Enter Last Name" name="lname" value="{!v.RegForm.LastName}"/>
        <br/>
        <lightning:input label="Enter Phone" name="phone" value="{!v.RegForm.Phone}"/>
        <br/>
        <lightning:input label="Enter Email" name="email" value="{!v.RegForm.Email}"/>
        <br/>
        <lightning:button label="Submit" onclick="{!c.doSubmit}"/>
    </div>
    <br/>
    <aura:if isTrue="{!v.showDetails}">
        <div class = "slds-size--3-of-8">
            <lightning:recordViewForm recordId="{!v.recordId}" objectApiName="Contact">
                <div class="slds-box">
                    <lightning:outputField fieldName="Name" />
                    <lightning:outputField fieldName="Phone" />
                    <lightning:outputField fieldName="Email" />
                </div>
            </lightning:recordViewForm>
        </div>
    </aura:if>
</aura:component>

Controller:
({
    doSubmit : function(component, event, helper) {
        var regForm = component.get("v.RegForm");
        var action = component.get("c.saveDetails");
        action.setParams({con  : regForm});
        action.setCallback(this, function(response) {
            var state = response.getState();          
            if (state === "SUCCESS") {
                var res = response.getReturnValue();
                component.set('v.recordId',res);
                component.set("v.showDetails", true);
                alert('Successfully Saved' + res);
                component.set('v.RegForm','');
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                    errors[0].message);
                    }
                } 
                else {
                    console.log(response.getReturnValue());
                }
            }
        });
        $A.enqueueAction(action);
    },
})

CSS:
.THIS {

}

.THIS.slds-size--3-of-8 {
    
    margin-left: 430px;
}

.THIS label.slds-form-element__label{
    
    font-size: 1.00rem;
    color: blue;
}

Application:
<aura:application extends="force:slds">
    <c:InsertAndDisplay/>
</aura:application>

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
Sid LightningSid Lightning
Thanks a lot.. I'll try this code. Can you help me with the other question that I have posted
Ajay K DubediAjay K Dubedi
Hi Sid,

Try following code for saving:

Component:
<aura:component>
    <lightning:input label="ShippindCardField1" name="ShippindCardField1" aura:id="ShippindCardField1"/>
    <lightning:input label="ShippindCardField2" name="ShippindCardField2" aura:id="ShippindCardField2"/>
    <lightning:button onclick="{!c.HandleClick}" label="Submit" />
</aura:component>

Controller:
({
    HandleClick : function(c, e, h) {
        try{
            let l = c.find('ShippindCardField1').get('v.value');
            let f = c.find('ShippindCardField2').get('v.value');
            let action = c.get('c.methodName');
            action.setParams({"ShippindCardField2": f, "ShippindCardField1": l});
            action.setCallback(this, function(r){
                console.log('State:'+r.getState());
            });
             $A.enqueueAction(action);
        }
        catch(e){
            console.log('Exception: '+e);
        }
    },
})

Class:
 
public class name{
    public static void (String ShippindCardField1, String ShippindCardField2.......){
            ShippindCard inst = new ShippindCard();
            inst.ShippindCardField1 = ShippindCardField1;
            inst.ShippindCardField2 = ShippindCardField2;
            insert inst;
    
    }
}

After this you can use lightning datatable component to display them, here is the link: http://www.sfdcpoint.com/salesforce/lightning-datatable-example-salesforce/

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com
Sid LightningSid Lightning
Hi Anas,

I am getting this error, while trying to execute your code

Uncaught Action failed: c:ProductAddressScreen$controller$handleSelect [component is not defined]


Function : object.saveAddress

Below is my code.
Component :

 <aura:attribute name="selectedAddress" type="Shipping_Address__c" default="{Name : '',
                                                                               Shipping_City__c : ''}"/>

 <lightning:buttonMenu iconName="utility:down" class="slds-float_right dropdown" onselect="{! c.handleSelect}">
                        <lightning:menuItem label="Save Address" value="Save Address"/>  
      </lightning:buttonMenu>

Controller : 

 if(selectedMenuItemValue == 'Save Address'){
                      helper.saveAddress(cmp, event, helper)
    }
                    

Helper : 

saveAddress : function (cmp, event, helper){
     var regForm = component.get("v.selectedAddress");
      var action = component.get("c.saveDetails");
 action.setParams({sha  : selectedAddress});

        action.setCallback(this, function(response) {

            var state = response.getState();         

            if (state === "SUCCESS") {

                var res = response.getReturnValue();

                component.set('v.recordId',res);

                component.set("v.showDetails", true);

                alert('Successfully Saved' + res);

                component.set('v.selectedAddress','');

            }

            else if (state === "ERROR") {

                var errors = response.getError();

                if (errors) {

                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + errors[0].message);
                   }
                }
                else {
                  console.log(response.getReturnValue());
                }
            }
     });
        $A.enqueueAction(action);
},

 
Khan AnasKhan Anas (Salesforce Developers) 
Sid, you have cmp as a parameter in function but you are using component.set() instead of cmp.set()
Sid LightningSid Lightning
I have done that change.. still showing the same error
Sid LightningSid Lightning
Hi Anas,

Can you please suggest. I have already done the change you suggested. still the same error
Sid LightningSid Lightning
Component :
  <aura:attribute name="accountId" type="Id"/>
    
    <aura:attribute name="selectedAddress" type="Shipping_Address__c" default="{Name : '',
                                                                               Shipping_City__c : ''}"/>
    <aura:attribute name="flatTypeValues" type="String[]"/>
    <aura:attribute name="error" type="String"/>
    <aura:attribute name="showDetails" type="boolean" default="false" />




<lightning:buttonMenu iconName="utility:down" class="slds-float_right dropdown" onselect="{! c.handleSelect}">
                        <lightning:menuItem label="Save Address" value="Save Address"/>  
                       <lightning:menuItem label="Confirm Address" value="Confirm Address"/>                        
                        <lightning:menuItem label="Search Pincode" value="Search Pincode" aura:id="searchPincode"/>
                    </lightning:buttonMenu>

Controller
handleSelect: function (cmp, event, helper) { 
        var selectedMenuItemValue = event.getParam("value");
        
         
        if(selectedMenuItemValue == 'Confirm Address'){
          //  console.log('confirming address');
          //  console.log('val:',cmp.get('v.selectedAddress'));
            helper.validateConfirmAdd(cmp, event, helper);
        }
        else if(selectedMenuItemValue == 'Save Address'){
                      helper.saveAddress(cmp, event, helper);
        }             
        else if(selectedMenuItemValue == 'Search Pincode'){
          //  console.log('search pincode');
            helper.enableSearchPincode(cmp, event, helper);
        }     
    }


Helper: 

saveAddress : function(cmp, event, helper){
     var regForm = cmp.get("v.selectedAddress");
      var action = cmp.get("c.saveDetails");
 action.setParams({sha : regForm});

        action.setCallback(this, function(response) {

            var state = response.getState();         

            if (state === "SUCCESS") {

                var res = response.getReturnValue();

                cmp.set('v.recordId',res);

                cmp.set("v.showDetails", true);

                alert('Successfully Saved' + res);

                cmp.set('v.selectedAddress','');

            }

            else if (state === "ERROR") {

                var errors = response.getError();

                if (errors) {

                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + errors[0].message);
                   }
                }
                else {
                  console.log(response.getReturnValue());
                }
            }
     });
        $A.enqueueAction(action);
Khan AnasKhan Anas (Salesforce Developers) 
I have tried your code in my org and I am not getting "component is not defined" error.
Sid LightningSid Lightning
You mean to say that the code is correct,

and data is getting saved
Deepali KulshresthaDeepali Kulshrestha
Hi Sid,
Greetings to you!

- Please use the code {Solved} : -
 
saveAddress : function (cmp, event, helper){
         var regForm = cmp.get("v.selectedAddress");
          var action = cmp.get("c.saveDetails");
     action.setParams({sha  : selectedAddress});

            action.setCallback(this, function(response) {

                var state = response.getState();         

                if (state === "SUCCESS") {

                    var res = response.getReturnValue();

                    cmp.set('v.recordId',res);

                    cmp.set("v.showDetails", true);

                    alert('Successfully Saved' + res);

                    cmp.set('v.selectedAddress','');

                }

                else if (state === "ERROR") {

                    var errors = response.getError();

                    if (errors) {

                        if (errors[0] && errors[0].message) {
                            console.log("Error message: " + errors[0].message);
                       }
                    }
                    else {
                      console.log(response.getReturnValue());
                    }
                }
         });
            $A.enqueueAction(action);
    },
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com
Sid LightningSid Lightning
Hi Deepali,

 I ave 6 fields that i want to save and display on page. Will this solution save all the 6 fields.. I dont see we are passing all the 6 fields. I havent wokred on lightning before.. so not sure
Sid LightningSid Lightning
Hi Deepali, 

Code is throwing error .

ProductAddressScreen$controller$handleSelect [selectedAddress is not defined]
 
Sid LightningSid Lightning
Hi Anas/Dipali,

Can you help me over the same/
Sid LightningSid Lightning
Anas, 

Can you please help
Sid LightningSid Lightning
Hi Anas,

Can you please help me with this code