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
ShaikAShaikA 

How to insert account and contact with single click in lightning component

Hi All,

I am new to lightining, i have a form as shown below when iam clicking on submit button after filling all the inputs, first i need to create account with firstname and lastname as Account name and after that i need to insert contact as child for that account.

it's means i need to create Account and its child contact, please help me to achieve this scenario.
User-added image

My component:
<aura:component controller="contactRegistrationController">
    <aura:attribute name="contacts" type="Contact[]"/>
     <aura:attribute name="accounts" type="Account[]"/>
    <aura:attribute name="newAccount" type="Account"
     default="{ 'sobjectType': 'Account',
                      'Name': ''
                    }"/>

<aura:attribute name="newContact" type="Contact"
     default="{ 'sobjectType': 'Contact',
                      'FirstName': '',
                    'LastName': '',
                    'Email': '',
                    'Phone': '','MailingStreet':'','MailingCity':'','MailingState':'','Zip':'','MailingCountry':'',
                    'Password__c': '' }"/>
    
    <!-- PAGE HEADER -->
    <div class="slds-page-header" role="banner">
      <div class="slds-grid">
        <div class="slds-col">
          <p class="slds-text-heading--label">Contact</p>
          <h1 class="slds-text-heading--medium">My Contact</h1>
        </div>
      </div>
    </div>
    <!-- / PAGE HEADER -->

    <!-- NEW EXPENSE FORM -->
    <div class="slds-col slds-col--padded slds-p-top--large">
 
  <div aria-labelledby="newcontactform">

  <!-- BOXED AREA -->
  <fieldset class="slds-box slds-theme--default slds-container--small">

    <legend id="newexpenseform" class="slds-text-heading--small 
      slds-p-vertical--medium">
      Add Contact
    </legend>

    <!-- CREATE NEW EXPENSE FORM -->
    <form class="slds-form--stacked">
        <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputText aura:id="fstname" label="First Name"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newContact.FirstName}"
                  required="true"/>
          </div></div>
      <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputText aura:id="lstname" label="Last Name"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newContact.LastName}"
                  required="true"/>
          </div>
     </div>
    
         <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputText aura:id="email" label="Email"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newContact.Email}"
                  required="true"/>
          </div>
     </div>
    <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputText aura:id="phone" label="Phone"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newContact.Phone}"
                  required=""/>
          </div></div>
          
      <div class="slds-form-element">
          <ui:button label="Submit"
              class="slds-button slds-button--brand"
              press="{!c.clickCreateContact}"/>
      </div>
    </form>
    <!-- / CREATE NEW EXPENSE FORM -->

  </fieldset>
  <!-- / BOXED AREA -->

</div>
<!-- / CREATE NEW EXPENSE -->

    </div>
    <!-- / NEW EXPENSE FORM -->
</aura:component>

Clinet side controller:
({
    clickCreateContact: function(component, event, helper) {
        console.log('inside click create contact');

        // Simplistic error checking
        var validExpense = true;

        // Name must not be blank
        var firstnameField = component.find("fstname");
        var frtname = firstnameField.get("v.value");
        
        if ($A.util.isEmpty(frtname)){
            validExpense = false;
            firstnameField.set("v.errors", [{message:"First name can't be blank."}]);
        }
        else {
            firstnameField.set("v.errors", null);
        }
        
        var lastnameField = component.find("lstname");
        var larname = lastnameField.get("v.value");
        if ($A.util.isEmpty(larname)){
            validExpense = false;
            lastnameField.set("v.errors", [{message:"Last Name can't be blank."}]);
        }
        else {
            // If the amount looks good, unset any errors...
            lastnameField.set("v.errors", null);
        }
        
       if(validExpense){
            // Create the new expense
            var newContact = component.get("v.newContact");
            var newAccount = component.get("v.newAccount");
            console.log("Create Contact: " + JSON.stringify(newContact));
            console.log("Create Account: " + JSON.stringify(newAccount));

           helper.createAccount(component, newAccount);
           helper.createContact(component, newContact);
           
       }
    },
})​

Helper:
({
    createAccount: function(component, account) {
        console.log('inside helper123');
        
    var action = component.get("c.saveAccount");
        console.log('after method called123');
    action.setParams({
        "account": account
        //component.get("v.contacts")
         
    });
        
    action.setCallback(this, function(response){
        var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
             //alert("From server: " + response.getReturnValue());

            var accounts = component.get("v.accounts");
            accounts.push(response.getReturnValue());
            component.set("v.accounts", accounts);
             
        }
    });
    $A.enqueueAction(action);
},    
    createContact: function(component, contact) {
        console.log('inside helper');
        
    var action = component.get("c.saveContact");
        console.log('after method called ');
    action.setParams({
        "Contact": contact
        //component.get("v.contacts")
         
    });
    action.setCallback(this, function(response){
        var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
            var contacts = component.get("v.contacts");
            contacts.push(response.getReturnValue());
            component.set("v.contacts", contacts);
             
        }
    });
    $A.enqueueAction(action);
},
    
})

server side controller:
public with sharing class contactRegistrationController {
     
    @AuraEnabled
    public static Account saveAccount(Account account) {
        upsert account;
        return account;
    }
    @AuraEnabled
    public static Contact saveContact(Contact Contact) {
        upsert Contact;
        return Contact;
    }
}

 
Best Answer chosen by ShaikA
ShaikAShaikA
I got solution

public with sharing class contactRegistrationController {
     
    @AuraEnabled
    public static Contact saveContact(Contact Contact) {
        account acc=new account();
        acc.Name=contact.FirstName +' ' +contact.LastName;
        insert acc;
        Contact.AccountId=acc.Id;
        upsert Contact;
        return Contact;
    }
}

All Answers

ShaikAShaikA
I got solution

public with sharing class contactRegistrationController {
     
    @AuraEnabled
    public static Contact saveContact(Contact Contact) {
        account acc=new account();
        acc.Name=contact.FirstName +' ' +contact.LastName;
        insert acc;
        Contact.AccountId=acc.Id;
        upsert Contact;
        return Contact;
    }
}
This was selected as the best answer
sfdcMonkey.comsfdcMonkey.com
hi ShaikA
there is no need to create a attribute for accont object also not need to create apex method for insert account i made little chnages in your code and now it's work as your requirement
component
<aura:component controller="contactRegistrationController">
    <aura:attribute name="contacts" type="Contact[]"/>
    <aura:attribute name="accounts" type="Account[]"/> 
<aura:attribute name="newContact" type="Contact"
        default="{ 'sobjectType': 'Contact',
                      'FirstName': '',
                    'LastName': '',
                    'Email': '',
                    'Phone': '','MailingStreet':'','MailingCity':'','MailingState':'','Zip':'','MailingCountry':'',
                    'Password__c': '' }"/>
    
    <!-- PAGE HEADER -->
    <div class="slds-page-header" role="banner">
      <div class="slds-grid">
        <div class="slds-col">
          <p class="slds-text-heading--label">Contact</p>
          <h1 class="slds-text-heading--medium">My Contact</h1>
        </div>
      </div>
    </div>
    <!-- / PAGE HEADER -->

    <!-- NEW EXPENSE FORM -->
    <div class="slds-col slds-col--padded slds-p-top--large">
 
  <div aria-labelledby="newcontactform">

  <!-- BOXED AREA -->
  <fieldset class="slds-box slds-theme--default slds-container--small">

    <legend id="newexpenseform" class="slds-text-heading--small 
      slds-p-vertical--medium">
      Add Contact
    </legend>

    <!-- CREATE NEW EXPENSE FORM -->
    <form class="slds-form--stacked">
        <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputText aura:id="fstname" label="First Name"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newContact.FirstName}"
                  required="true"/>
          </div></div>
      <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputText aura:id="lstname" label="Last Name"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newContact.LastName}"
                  required="true"/>
          </div>
     </div>
    
         <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputText aura:id="email" label="Email"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newContact.Email}"
                  required="true"/>
          </div>
     </div>
    <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputText aura:id="phone" label="Phone"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newContact.Phone}"
                  required=""/>
          </div></div>
          
      <div class="slds-form-element">
          <ui:button label="Submit"
              class="slds-button slds-button--brand"
              press="{!c.clickCreateContact}"/>
      </div>
    </form>
    <!-- / CREATE NEW EXPENSE FORM -->

  </fieldset>
  <!-- / BOXED AREA -->

</div>
<!-- / CREATE NEW EXPENSE -->

    </div>
    <!-- / NEW EXPENSE FORM -->
</aura:component>
js controller
({
    clickCreateContact: function(component, event, helper) {
        console.log('inside click create contact');

        // Simplistic error checking
        var validExpense = true;

        // Name must not be blank
        var firstnameField = component.find("fstname");
        var frtname = firstnameField.get("v.value");
        
        if ($A.util.isEmpty(frtname)){
            validExpense = false;
            firstnameField.set("v.errors", [{message:"First name can't be blank."}]);
        }
        else {
            firstnameField.set("v.errors", null);
        }
        
        var lastnameField = component.find("lstname");
        var larname = lastnameField.get("v.value");
        if ($A.util.isEmpty(larname)){
            validExpense = false;
            lastnameField.set("v.errors", [{message:"Last Name can't be blank."}]);
        }
        else {
            // If the amount looks good, unset any errors...
            lastnameField.set("v.errors", null);
        }
        
       if(validExpense){
            // Create the new expense
            var newContact = component.get("v.newContact");
            //var newAccount = component.get("v.newAccount");
            console.log("Create Contact: " + JSON.stringify(newContact));
           // console.log("Create Account: " + JSON.stringify(newAccount));

           //helper.createAccount(component, newAccount);
           helper.createContact(component, newContact);
           
       }
    },
})
helper
({
   
    createContact: function(component, contact) {
        console.log('inside helper');
        
    var action = component.get("c.saveContact");
        console.log('after method called ');
    action.setParams({
        "Contact": contact
        //component.get("v.contacts")
         
    });
    action.setCallback(this, function(response){
        var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
            var contacts = component.get("v.contacts");
            contacts.push(response.getReturnValue());
            component.set("v.contacts", contacts);
            alert('wooow child contact with parent account insert successfully');
             
        }
    });
    $A.enqueueAction(action);
},
    
})
Apex class (....add account here :) )
public with sharing class contactRegistrationController {

    @AuraEnabled
    public static Contact saveContact(Contact Contact) {
        account acc = new account();
        acc.name = Contact.FirstName +' '+ Contact.LastName;
        insert acc;
        Contact.AccountId = acc.id;
        insert Contact;
        return Contact;
    }
}
if any issue you can ask here
mark it best answer if its helps you :)
Thanks



 
ShaikAShaikA
Thanks for your replay Piyush, you are right no need to created attribute for account and method, i have removed it.

Regards,
Shaik
sfdcMonkey.comsfdcMonkey.com
Plesure If it work for you mark it best answer so it make proper solution for others:)
ShaikAShaikA
Hi Piyush,

Please help me to write details page navigation, once contact record created in above scenario.

Regards,
Shaik
sfdcMonkey.comsfdcMonkey.com
HI
so you want display new insert contact disply on page aftere insert it ? i am right ?
ShaikAShaikA
Hi Piyush,

Thanks for your replay, actually my scenario is landing to different page(detail page) once contact record is insert.
Same functionality we can achieve with pageReference in VF page as below, but here in lightning I don’t have any idea how we can achieve same scenario.
 
Public pagerefrence newcotact(){
Insert contact;
pageReference page=new pageReference(‘/apex/detailspage?id=’+contact.id);
return page;
}
 
Please help me on it, thanks in advance.
Shaik