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
Haneef SHaneef S 

insert a new record using custom button

Hi All,
I am new to lightning, can some one please help me with the below code:
I have my existing code that displays accounts and when clicked particular account it shows its own contacts.
Now, on the same page there should be one button for Add Account. On click of this button, popup will ask for account details and after click on submit button this new account will add to database, go to previous page and previous page also will refresh.

when I click on preview I get below error:
User-added image

Below is my code:
component:
<aura:component controller="AccountPagination" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <ltng:require styles="/resource/SLDS244/styles/salesforce-lightning-design-system.css" />
    
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    
    <div class="slds-page-header" role="banner" >
        <div class="slds-grid">
            <div class="slds-col" >
                <h1 class="slds-text-heading--medium">Accounts List</h1>
            </div>
        </div>
    </div>
    <aura:attribute name="acccountList" type="Account[]" />
    <aura:attribute name="contacts" type="Contact[]"/>
    <aura:attribute name="paginationList" type="Account[]"/>
    <aura:attribute name="pageSize" type="Integer" default="15"/>
    <aura:attribute name="totalSize" type="Integer"/>
    <aura:attribute name="start" type="Integer" />
    <aura:attribute name="end" type="Integer"/>
    
    <table class="slds-table slds-table--bordered ">
        <thead>
            <tr style="color:Grey;font-weight:bold">
                <!--<td> <div class="slds-page-header" role="banner" >
                    <div class="slds-grid">
                        <div class="slds-col" >
                            <th><h1 class="slds-text-heading-/-medium">Id</h1></th>
                            
                        </div>
                    </div>
                    </div></td>-->
                <td>  <div class="slds-page-header" role="banner" >
                    <div class="slds-grid">
                        <div class="slds-col" >
                            <th><h1 class="slds-text-heading--medium">Name</h1></th>
                        </div>
                    </div>
                    </div></td>
                
                <td>  <div class="slds-page-header" role="banner" >
                    <div class="slds-grid">
                        <div class="slds-col" >
                            <th><h1 class="slds-text-heading--medium">AccountNumber</h1></th>
                        </div>
                    </div>
                    </div></td>
                
                <!--<td> <div class="slds-page-header" role="banner" >
                    <div class="slds-grid">
                        <div class="slds-col" >
                            <th><h1 class="slds-text-heading-/-medium">AccountOwnerId</h1></th>
                        </div>
                    </div>
                    </div></td>-->
                
                <!--<th>Id</th>
                <th>Name</th>
                <th>Phone</th>
                <th>AccountNumber</th>
                <th>BillingAddress</th>-->
            </tr>
        </thead>
        <tbody>
            <aura:iteration items="{!v.paginationList}" var="item">
                <tr>
                    <!--<td><lightning:input value="{!item.Id}"/></td> 
                    <td><lightning:input value="{!item.Name}"/></td>
                    
                    <td><lightning:input value="{!item.AccountNumber}"/></td>
                    <td><lightning:input value="{!item.OwnerId}"/></td>
                    <td><lightning:input value="{!item.Owner.Name}"/></td>-->
                   <!--<td><ui:outputText value="{!item.Id}" /></td>-->
                    
                    <td><a href="javascript:void(0);" onclick="{!c.Clicked}" data-value="{!item.Id}">{!item.Name}
                    </a></td>
                    
                    <td><ui:outputText value="{!item.AccountNumber}"/></td>
                    
                    <!--<td><ui:outputText value="{!item.OwnerId}"/></td>-->
                    
                </tr>
            </aura:iteration>
            <!--  <lightning:button label="Previous" disabled="{!v.start == 0}"  onclick="{!c.previous}" />
            <lightning:button label="Next" disabled="{!v.end >= v.totalSize}" onclick="{!c.next}" />-->
        </tbody>
    </table>
    <lightning:button label="Previous" disabled="{!v.start == 0}"  onclick="{!c.previous}" />
    <lightning:button label="Next" disabled="{!v.end >= v.totalSize}" onclick="{!c.next}" />
    <lightning:button label="Create New account" onclick="{!c.createRecord}" />
    
    <div class="slds-page-header" role="banner" >
        <div class="slds-grid">
            <div class="slds-col" >
                <h1 class="slds-text-heading--medium">Contacts associated with account</h1>
            </div>
        </div>
    </div>
    
    <table class="slds-table slds-table--bordered ">
        <thead>
            <tr style="color:Grey;font-weight:bold">
                <td> <div class="slds-page-header" role="banner" >
                    <div class="slds-grid">
                        <div class="slds-col" >
                            <th><h1 class="slds-text-heading--medium">Contact Id</h1></th>
                            
                        </div>
                    </div>
                    </div></td>
                <td>  <div class="slds-page-header" role="banner" >
                    <div class="slds-grid">
                        <div class="slds-col" >
                            <th><h1 class="slds-text-heading--medium">Contact Name</h1></th>
                        </div>
                    </div>
                    </div></td>
                <td>  <div class="slds-page-header" role="banner" >
                    <div class="slds-grid">
                        <div class="slds-col" >
                            <th><h1 class="slds-text-heading--medium">Account Id</h1></th>
                        </div>
                    </div>
                    </div></td>
                 <td>  <div class="slds-page-header" role="banner" >
                    <div class="slds-grid">
                        <div class="slds-col" >
                            <th><h1 class="slds-text-heading--medium">Account Name</h1></th>
                        </div>
                    </div>
                    </div></td>
                 
            </tr>
        </thead>
        <tbody>
            <aura:iteration items="{!v.contacts}" var="con">
                <tr>
                     <td><ui:outputText value="{!con.Id}" /></td>
                    <td><ui:outputText value="{!con.Name}" /></td>
                    <td><ui:outputText value="{!con.AccountId}" /></td>
                    <td><ui:outputText value="{!con.Account.Name}" /></td>
                    
                </tr>
            </aura:iteration>
        </tbody>
    </table>
</aura:component>
Accountpaginationcontroller.js
({
    doInit : function(component, event, helper)
    {
        var pageSize = component.get("v.pageSize");
        
        var action = component.get("c.getAccounts");
        action.setCallback(this, function(response) 
                           {
                               var state = response.getState();
                               if (component.isValid() && state === "SUCCESS") 
                               {
                                   console.log(response.getReturnValue());
                                   component.set('v.acccountList', response.getReturnValue());
                                   
                                   component.set("v.totalSize", component.get("v.acccountList").length);
                                   component.set("v.start",0);
                                   component.set("v.end",pageSize-1);
                                   
                                   var paginationList = [];
                                   for(var i=0; i< pageSize; i++)
                                   {
                                       paginationList.push(response.getReturnValue()[i]);    
                                   }
                                   
                                   component.set('v.paginationList', paginationList);
                               }
                           });
        $A.enqueueAction(action);
    },
    next : function(component, event, helper) 
    {
        var accountList = component.get("v.acccountList");
        var end = component.get("v.end");
        var start = component.get("v.start");
        var pageSize = component.get("v.pageSize");
        var paginationList = [];
        
        var counter = 0;
        for(var i=end+1; i<end+pageSize+1; i++)
        {
            if(accountList.length > end)
            {
                paginationList.push(accountList[i]);
                counter ++ ;
            }
        }
        start = start + counter;
        end = end + counter;
        
        component.set("v.start",start);
        component.set("v.end",end);
        
        component.set('v.paginationList', paginationList);
    },
    previous : function(component, event, helper) 
    {
        var accountList = component.get("v.acccountList");
        var end = component.get("v.end");
        var start = component.get("v.start");
        var pageSize = component.get("v.pageSize");
        var paginationList = [];
        
        var counter = 0;
        for(var i= start-pageSize; i < start ; i++)
        {
            if(i > -1)
            {
                paginationList.push(accountList[i]);
                counter ++;
            }
            else
            {
                start++;
            }
        }
        start = start - counter;
        end = end - counter;
        
        component.set("v.start",start);
        component.set("v.end",end);
        
        component.set('v.paginationList', paginationList);
    },
    Clicked : function(component, event, helper){
        var ctarget = event.currentTarget;
        var id_str = ctarget.dataset.value;
        console.log(id_str);
        
        var action = component.get("c.getContactRecords");
        action.setParams({ accId :  id_str});
        action.setCallback(this, function(response) {
            var state = response.getState(); //Checking response status
            console.log("contactsss... "+JSON.stringify(response.getReturnValue()));
            if (component.isValid() && state === "SUCCESS"){
                if(response.getReturnValue() !=''){
                    component.set("v.contacts", response.getReturnValue());
                }
                else{
                    alert('contacts are not available for this account');
                    //  Adding values in Aura attribute variable. 
                    
                }
            }    });
        $A.enqueueAction(action);
    },
    createRecord: function(component, event, helper) {
      var createRecordEvent = $A.get("e.force:createRecord");
      createRecordEvent.setParams({
         "entityApiName": "Account" // using account standard object for this sample
      });
      createRecordEvent.fire();
   }
})
accountpagination.apxc
public with sharing class AccountPagination 
{
    /*@AuraEnabled
public static List<Account> getAccounts()
{
List<Account> accs = [SELECT Id, Name,Phone,AccountNumber,BillingAddress,Fax,OwnerId,Owner.Name,(SELECT Id,FirstName,LastName,Email from contacts) FROM Account];
return accs;
}*/
    @AuraEnabled
    public static List<Account> getAccounts() {
        return new List<Account>([SELECT Id, Name,Phone,AccountNumber,BillingAddress,Fax,OwnerId,Owner.Name FROM Account]);
    }
    @AuraEnabled
    public static List<Contact> getContactRecords(string accId) {
        return new List<Contact>([Select id,Name,Account.Name,AccountId from Contact Where AccountId =: accId LIMIT 100]);
    }
}
accountpaginationapp.app:
<aura:application >
    <c:AccountPagination/>
</aura:application>

Can anyone please help 
Khan AnasKhan Anas (Salesforce Developers) 
Hi Haneef,

Greetings to you!

Below is the sample code which I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Component:
<aura:component controller="PopupFormC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute name="PageHeading" type="String" default="MODAL POPUP" />
    <aura:attribute name="mydata" type="List"/>
    <aura:attribute name="accdata" type="List"/>
    <aura:attribute name="mydata1" type="List"/>
    <aura:attribute name="accForm" type="Account" default="{'sobjectType' : 'Account'}"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.doinit}" />
    <aura:handler event="force:refreshView" action="{!c.doinit}" />
    
    <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/>
    
    <lightning:button label="Create Account PopUp"
                      iconName="utility:new_window"
                      iconPosition="left"
                      variant="brand"
                      onclick="{!c.newPopup}"
                      />
    
    <div role="dialog" tabindex="-1" aria-labelledby="header43" aura:id="Modalbox1" class="slds-modal slds-modal_large">
        <div class="slds-modal__container" style="width: 65%;">
            <div class="slds-modal__header">
                ACCOUNT
            </div>
            
            <div class="slds-modal__content slds-p-around--medium">
                <div class="slds-p-left_xx-large slds-p-right_xx-large">
                    <div class="slds-page-header" style="padding-top: 9px; padding-bottom: 9px;, padding-right: 9px;, padding-left: 10px;">
                        <h3 style="font-size: 1rem;" title="">Account Information</h3>
                    </div> 
                </div>    
                <div class="slds-grid slds-p-top_medium">
                    <div class="slds-size_6-of-12 slds-p-left_xx-large slds-p-horizontal_x-large " >
                        <lightning:input label="Account Name" name="myname" value="{!v.accForm.Name}"/> 
                    </div>
                    <div class="slds-size_5-of-12 slds-p-left_xx-small slds-p-horizontal_x-large " >
                        <lightning:input label="Phone" name="myname" value="{!v.accForm.Phone}"/> 
                    </div>
                </div>
                <div class="slds-grid slds-p-top_x-small">
                    <div class="slds-size_6-of-12 slds-p-left_xx-large slds-p-horizontal_x-large " >
                        <lightning:input label="Account Number" name="mynumber" value="{!v.accForm.AccountNumber}"/> 
                    </div>
                    <div class="slds-size_5-of-12 slds-p-left_xx-small slds-p-horizontal_x-large " >
                        <lightning:input label="Description" name="myphone" value="{!v.accForm.Description}"/> 
                    </div>
                </div>
            </div>
            <div class="slds-modal__footer">
                <lightning:button label="Save" onclick="{!c.saveModal}" />
                <lightning:button label="close" onclick="{!c.closeNewModal}" />
            </div>
        </div>
    </div>
    
    <div class="slds-section slds-is-open">
        <h3 class="slds-section__title slds-theme_shade">
            <span class="slds-truncate slds-p-horizontal_small" title="Section Title">Accounts</span>
        </h3>
        <br/>
        <table class="slds-table slds-table--bordered slds-table--striped slds-table--cell-buffer slds-table--fixed-layout">
            <thead>
                <tr class="slds-text-heading--label">
                    <th scope="col"><div class="slds-truncate" title="Account Name">Account Name</div></th>
                    <th scope="col"><div class="slds-truncate" title="Phone">Phone</div></th>
                </tr>
            </thead>
            <tbody>
                <aura:iteration items="{!v.mydata}" var="row" indexVar="index">
                    <tr>
                        <th scope="row"><div class="slds-truncate" >
                            <a onclick="{!c.showContact}" value="{!row}" data-index="{!index}">{!row.Name}</a>
                            </div></th>
                        <td><div class="slds-truncate" title="{!row.Phone}">{!row.Phone}</div></td>
                    </tr>
                </aura:iteration>
            </tbody>
        </table>
    </div>
    
    <br/><br/>
    
        <div class="slds-section slds-is-open">
        <h3 class="slds-section__title slds-theme_shade">
            <span class="slds-truncate slds-p-horizontal_small" title="Section Title">Related Contacts</span>
        </h3>
        <br/>
        <table class="slds-table slds-table--bordered slds-table--striped slds-table--cell-buffer slds-table--fixed-layout">
            <thead>
                <tr class="slds-text-heading--label">
                    <th scope="col"><div class="slds-truncate" title="Account Name">Account Name</div></th>
                    <th scope="col"><div class="slds-truncate" title="Conatct Name">Contact Name</div></th>
                </tr>
            </thead>
            <tbody>
                <aura:iteration items="{!v.mydata1}" var="row1" indexVar="index1">
                    <tr>
                        <td><div class="slds-truncate" title="{!row1.Account.Name}">{!row1.Account.Name}</div></td>
                        <td><div class="slds-truncate" title="{!row1.Name}">{!row1.Name}</div></td>
                    </tr>
                </aura:iteration>
            </tbody>
        </table>
    </div>
</aura:component>

Controller:
({
    doinit : function(component, event, helper) {
        var action = component.get('c.fetchAcc');
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);
            }
            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("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    newPopup : function(component, event, helper){
        var cmpTarget = component.find('Modalbox1');
        var cmpBack = component.find('Modalbackdrop');
        $A.util.addClass(cmpTarget, 'slds-fade-in-open');
        $A.util.addClass(cmpBack, 'slds-backdrop--open');
    },
    
    saveModal : function(component, event, helper){
        var regForm = component.get("v.accForm");
        var action = component.get("c.saveDetails");
        action.setParams({regForm1  : regForm});
        action.setCallback(this, function(response) {
            var state = response.getState();          
            if (state === "SUCCESS") {
                $A.get('e.force:refreshView').fire();
                var cmpTarget = component.find('Modalbox1');
                var cmpBack = component.find('Modalbackdrop');
                $A.util.removeClass(cmpBack,'slds-backdrop--open');
                $A.util.removeClass(cmpTarget, 'slds-fade-in-open');
                
            }
            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);
    },
    
    closeNewModal : function(component, event, helper){
        var cmpTarget = component.find('Modalbox1');
        var cmpBack = component.find('Modalbackdrop');
        $A.util.removeClass(cmpBack,'slds-backdrop--open');
        $A.util.removeClass(cmpTarget, 'slds-fade-in-open');
    },
    
    showContact : function(component, event, helper){
        var idx = event.target.getAttribute('data-index');
        console.log('idx---->>> ' + idx);
        var rowRecord = component.get("v.mydata")[idx];
        console.log('rowRecord--->>> ' + JSON.stringify(rowRecord));        
        component.set('v.accdata',rowRecord);
        
        var action = component.get('c.getContacts');
        action.setParams({accId : rowRecord.Id});
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                console.log("allValues--->>> " + JSON.stringify(allValues));
                component.set('v.mydata1', allValues);
            }
            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("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    },
})

CSS:
.THIS {
}

.THIS .slds-section__title{
    background-color: YellowGreen;
    color: white
}
.THIS .slds-modal__header{
    background-color: OliveDrab;
    color: white
}

Apex:
public class PopupFormC {

    @AuraEnabled
    public static List<Account> fetchAcc (){
        return [SELECT Id, Name, Phone FROM Account ORDER BY CreatedDate desc LIMIT 10];
    }

	@AuraEnabled
    public static void saveDetails (Account regForm1){ 
    	INSERT regForm1;
    }
    
    @AuraEnabled
    public static List<Contact> getContacts (String accId){
        return new List<Contact>([SELECT Id, Name, Account.Name, AccountId FROM Contact WHERE AccountId =:accId LIMIT 10]);
    }
}

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.

Thanks and Regards,
Khan Anas
Haneef SHaneef S
Hi Anas Khan,
Thank you so much for your response.
My requirement is partially solved and got output with out errors.
when I click on create account nothing happens ,
requirement is when clicked on the button, a pop up should open and ask for mandatory details and when clicked save , the new account should visible on the list of existing accounts, when clicked cancel the pop up should be closed.

Thanks,
Haneef
Khan AnasKhan Anas (Salesforce Developers) 
Hi Haneef,

The above code which I have shared will fulfill your requirement. You can see I have used a lightning button with name Create Account PopUp. If you click on it, a popup will open with Account's input fields. 
 
<lightning:button label="Create Account PopUp"
                      iconName="utility:new_window"
                      iconPosition="left"
                      variant="brand"
                      onclick="{!c.newPopup}"
                      />

Please go through my code, it will definitely solve your problem. I have checked it in my org, it is working fine.

Regards,
Khan Anas