+ Start a Discussion
Athira VenugopalAthira Venugopal 

Unable to create a contact using Lightning aura components

ContactComponent.cmp
<aura:component controller ="ContactController " implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    <aura:attribute name = "conList" type = "Contact"></aura:attribute>
    <lightning:input type ="text" label = "First Name" value="{!v.conList.FirstName}" ></lightning:input>
     <lightning:input type ="text" label = "Last Name" value="{!v.conList.LastName}"></lightning:input>
     <lightning:input  type ="tel" label = "Phone" value="{!v.conList.Phone}"></lightning:input>
     <lightning:input type ="email" label = "Email"  value="{!v.conList.Email}" ></lightning:input>
     <lightning:button variant="brand" label="Create" onclick="{!c.handleClick}" class="slds-m-left_x-small"></lightning:button>
</aura:component>

ContactComponentController.js

({
    handleClick : function(component, event, helper) {
        
        console.log("HIIIIIII" + conlist);
        var action = component.get("c.createContact");
        action.setParams({
           ac : component.get("v.conList")
        });
        action.setCallback(this,function(response){
            if(response.getState() == 'SUCCESS') {
            alert("Updated successfully");
            
        }
        });
    $A.enqueueAction(action);
    }
})

ContactController.apxc

public class ContactController {
    @auraEnabled
    public static void createContact( Contact c) {
      
        insert c;
    }

}

Is there any mistake in my code
Best Answer chosen by Athira Venugopal
ANUTEJANUTEJ (Salesforce Developers) 
Hi Athira,

I was using the below code for create a custom record and I was able to create a new record can you try this code once:

Component:
<aura:component controller="createRecordController"  implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
	
 <!-- attributes to capture account fields -->
  <aura:attribute name="name" type="String"/>
  <aura:attribute name="type" type="String"/>
  <aura:attribute name="annualRevenue" type="Currency"/>
    
 <!-- Picklist options attribute -->
  <aura:attribute name="options" 
                  type="list" 
      default="[
                {'label': 'Prospect', 'value': 'Prospect'},
                {'label': 'Customer - Direct', 'value': 'Customer - Direct'},
                {'label': 'Customer - Channel', 'value': 'Customer - Channel'},
                {'label': 'Channel Partner / Reseller', 'value': 'Channel Partner / Reseller'},
                {'label': 'Installation Partner', 'value': 'Installation Partner'},
                {'label': 'Technology Partner', 'value': 'Technology Partner'},
                {'label': 'Other', 'value': 'Other'}                               ]" 
  description="Below attribute will define picklist values if you want dynamic values then you can query that from the database and set those values"/>
    
  <center>
      <h1 class="inlineTitle slds-p-top--large slds-p-horizontal--medium slds-p-bottom--medium slds-text-heading--medium" 
            style="font-size:20px">
            Custom Create Account
            <hr size="3" noshade=""></hr>
      </h1>
  </center>
    
   <h2 class="slds-section__title slds-theme--shade primaryPaletteBorder test-id__section-header-container"> 
        New Account Information
   </h2>
    
    <div class="slds-p-around_medium">
        <lightning:input name="Name" 
                         required="true" 
                         value="{!v.name}" 
                         label="Name" 
                         maxlength="255"/>
        
        <lightning:combobox name="Status" 
                            label="Status" 
                            value="inProgress" 
                            placeholder="Select Progress" 
                            options="{!v.options}" 
                            onchange="{!c.handleChange}"/>
        
        <lightning:input type="number" 
                         name="Annual Revenue"
                         label="Annual Revenue" 
                         value="{!v.annualRevenue}" 
                         formatter="currency"
                         fieldLevelHelp="Please enter in numbers"/>
        
    </div> 
    <center>
        <lightning:button variant="Brand" 
                          label="Save" 
                          title="Save" 
                          onclick="{!c.save}"/>
        <lightning:button variant="Neutral" 
                          label="Cancel" 
                          title="Cancel" 
                          onclick="{!c.cancel}"/>
    </center>
</aura:component>

Controller:
 
({    
  handleChange: function (component, event) {
  // This will contain the string of the "value" attribute of the selected option
        var selectedOptionValue = event.getParam("value");
        component.set("v.type", selectedOptionValue);
    },
    
  save : function (component, event, helper){
        //get all the inputs from form
        var name = component.get("v.name");
        var type = component.get("v.type");
        var annualRevenue = component.get("v.annualRevenue");
        
        //Error handling: if any field is undefined
        if(name == undefined || type == undefined || annualRevenue == undefined)
        {
         helper.showToast('Ooops !', 'Please fill up all the information', 'error');
        }
        else
        {
    //if everything is okey then make server call   
      var action = component.get("c.saveAccount"); 
         action.setParams({
           name : name, 
           accountType : type,
           revenue : annualRevenue
            }); 
     action.setCallback(this,function(response){
     var state = response.getState();
 //if callback is Success then show toast message and close the modal popup
         if(state === "SUCCESS")
         {
//pass parameters to helper showToast method  
  helper.showToast('Success !', 'Record Inserted Successfully', 'success');
           $A.get("e.force:closeQuickAction").fire();
         }
       });
          $A.enqueueAction(action);
      }  
    },
    
    cancel : function(component, helper, event)
    {
        //Below line of code will close the modal popup
        $A.get("e.force:closeQuickAction").fire();   
    }
})

Helper:
 
({
   //dynamic toast message alert function
   //It will take dynamic input parameters from controller methods
   //We used this for displaying error and success 
    showToast : function(title, message, error) {
        let toastParams = {
            title: title,
            message: message, // Error message
            type: error
        };
        let toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams(toastParams);
        toastEvent.fire();
    }
})

Controller:
 
public class createRecordController {

    

@AuraEnabled

 public static Account saveAccount(String name, String accountType, Decimal revenue)

    {
        Account acc = new Account();
        acc.Name = name;
        acc.Type = accountType;
        acc.AnnualRevenue = revenue;
        insert acc;
        return acc;
    }
}

Let me know in case if this comes in handy and in case if this helps can you please mark this as the best answer so that it can be used by others in the future.

Regards,
Anutej

All Answers

ANUTEJANUTEJ (Salesforce Developers) 
Hi Athira,

I was using the below code for create a custom record and I was able to create a new record can you try this code once:

Component:
<aura:component controller="createRecordController"  implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
	
 <!-- attributes to capture account fields -->
  <aura:attribute name="name" type="String"/>
  <aura:attribute name="type" type="String"/>
  <aura:attribute name="annualRevenue" type="Currency"/>
    
 <!-- Picklist options attribute -->
  <aura:attribute name="options" 
                  type="list" 
      default="[
                {'label': 'Prospect', 'value': 'Prospect'},
                {'label': 'Customer - Direct', 'value': 'Customer - Direct'},
                {'label': 'Customer - Channel', 'value': 'Customer - Channel'},
                {'label': 'Channel Partner / Reseller', 'value': 'Channel Partner / Reseller'},
                {'label': 'Installation Partner', 'value': 'Installation Partner'},
                {'label': 'Technology Partner', 'value': 'Technology Partner'},
                {'label': 'Other', 'value': 'Other'}                               ]" 
  description="Below attribute will define picklist values if you want dynamic values then you can query that from the database and set those values"/>
    
  <center>
      <h1 class="inlineTitle slds-p-top--large slds-p-horizontal--medium slds-p-bottom--medium slds-text-heading--medium" 
            style="font-size:20px">
            Custom Create Account
            <hr size="3" noshade=""></hr>
      </h1>
  </center>
    
   <h2 class="slds-section__title slds-theme--shade primaryPaletteBorder test-id__section-header-container"> 
        New Account Information
   </h2>
    
    <div class="slds-p-around_medium">
        <lightning:input name="Name" 
                         required="true" 
                         value="{!v.name}" 
                         label="Name" 
                         maxlength="255"/>
        
        <lightning:combobox name="Status" 
                            label="Status" 
                            value="inProgress" 
                            placeholder="Select Progress" 
                            options="{!v.options}" 
                            onchange="{!c.handleChange}"/>
        
        <lightning:input type="number" 
                         name="Annual Revenue"
                         label="Annual Revenue" 
                         value="{!v.annualRevenue}" 
                         formatter="currency"
                         fieldLevelHelp="Please enter in numbers"/>
        
    </div> 
    <center>
        <lightning:button variant="Brand" 
                          label="Save" 
                          title="Save" 
                          onclick="{!c.save}"/>
        <lightning:button variant="Neutral" 
                          label="Cancel" 
                          title="Cancel" 
                          onclick="{!c.cancel}"/>
    </center>
</aura:component>

Controller:
 
({    
  handleChange: function (component, event) {
  // This will contain the string of the "value" attribute of the selected option
        var selectedOptionValue = event.getParam("value");
        component.set("v.type", selectedOptionValue);
    },
    
  save : function (component, event, helper){
        //get all the inputs from form
        var name = component.get("v.name");
        var type = component.get("v.type");
        var annualRevenue = component.get("v.annualRevenue");
        
        //Error handling: if any field is undefined
        if(name == undefined || type == undefined || annualRevenue == undefined)
        {
         helper.showToast('Ooops !', 'Please fill up all the information', 'error');
        }
        else
        {
    //if everything is okey then make server call   
      var action = component.get("c.saveAccount"); 
         action.setParams({
           name : name, 
           accountType : type,
           revenue : annualRevenue
            }); 
     action.setCallback(this,function(response){
     var state = response.getState();
 //if callback is Success then show toast message and close the modal popup
         if(state === "SUCCESS")
         {
//pass parameters to helper showToast method  
  helper.showToast('Success !', 'Record Inserted Successfully', 'success');
           $A.get("e.force:closeQuickAction").fire();
         }
       });
          $A.enqueueAction(action);
      }  
    },
    
    cancel : function(component, helper, event)
    {
        //Below line of code will close the modal popup
        $A.get("e.force:closeQuickAction").fire();   
    }
})

Helper:
 
({
   //dynamic toast message alert function
   //It will take dynamic input parameters from controller methods
   //We used this for displaying error and success 
    showToast : function(title, message, error) {
        let toastParams = {
            title: title,
            message: message, // Error message
            type: error
        };
        let toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams(toastParams);
        toastEvent.fire();
    }
})

Controller:
 
public class createRecordController {

    

@AuraEnabled

 public static Account saveAccount(String name, String accountType, Decimal revenue)

    {
        Account acc = new Account();
        acc.Name = name;
        acc.Type = accountType;
        acc.AnnualRevenue = revenue;
        insert acc;
        return acc;
    }
}

Let me know in case if this comes in handy and in case if this helps can you please mark this as the best answer so that it can be used by others in the future.

Regards,
Anutej
This was selected as the best answer
Herish SurendranHerish Surendran
Hi Athira,

I would suggest to use Lightning:RecordEditForm Insteead using this much big lines of code.

Something Like this:
<aura:component>
    <lightning:recordEditForm aura:id="recordEditForm"
                           objectApiName="Contact">
        <lightning:messages />
        <lightning:inputField fieldName="Name" />
        <lightning:button class="slds-m-top_small" type="submit" label="Create new" />
    </lightning:recordEditForm>
</aura:component>

You don't need to use apex to insert contact record, all that is taken care by Salesforce.

Lightning:RecordEditForm (https://developer.salesforce.com/docs/component-library/bundle/lightning:recordEditForm/documentation) - Salesforce Documentation
Trailhead Module (https://trailhead.salesforce.com/content/learn/projects/workshop-lightning-programmatic/handle-data-with-recordeditform) - Trailhead module on Lightning:RecordEditForm
Herish SurendranHerish Surendran
I hope it helps. Mark this as  solved, so that others facing similar issue can use this as reference.
ANUTEJANUTEJ (Salesforce Developers) 
I have made few changes to the above code you have provided and I was able to use it to create a new record.
 
<aura:component controller ="ContactController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
   
    <aura:attribute name = "conList" type = "Contact" default="{ 'sobjectType': 'Contact'}"></aura:attribute>
    
    <lightning:button aura:id="saveId"
                                  label="Save"   
                                  onclick="{!c.handleClick}"/>
    
    <lightning:input type ="String" label = "First Name" value="{!v.conList.FirstName}" ></lightning:input>
     <lightning:input type ="String" label = "Last Name" value="{!v.conList.LastName}"></lightning:input>
     <lightning:input  type ="number" label = "Phone" value="{!v.conList.Phone}"></lightning:input>
     <lightning:input type ="email" label = "Email"  value="{!v.conList.Email}" ></lightning:input>
    
</aura:component>
 
({
    handleClick : function(component, event, helper) {
        
        
        var action = component.get("c.createContact");
        action.setParams({"c": component.get("v.conList")});
        /*action.setParams({
           ac : component.get("v.conList")
        });*/
        action.setCallback(this,function(response){
            var state = response.getState();
            //If response from server side is <SUCCESS>, then we will display a success message.
            if (state === "SUCCESS"){
                //Success message display logic.
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "Success!",
                    "message": "Student record has been inserted successfully."
                });
                toastEvent.fire();
            }else if (state === "INCOMPLETE") {
                //Offline message display logic.
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "OFFLINE!",
                    "message": "You are in offline."
                });
                toastEvent.fire();
            }else if (state === "ERROR") {
                //Error message display logic.
                var errors = response.getError();
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "ERROR!",
                    "message": errors[0].message
                });
                toastEvent.fire();
            }else {
                //Unknown message display logic.
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "UNKOWN!",
                    "message": "Unknown error."
                });
                toastEvent.fire();
            }
        });
    $A.enqueueAction(action);
    }
})
 
public with sharing class ContactController {
    @AuraEnabled
    public static void createContact( Contact c) {
      
        insert c;
    }

}

Changes I made are:

>> in the controller class made it with sharing.

>>and while setting parameters you are doing it wrongly instead of using this: action.setParams({
           ac : component.get("v.conList")
        });
//try changing ac to c as the prarmeter in apex class is c and not ac
I used action.setParams({"c": component.get("v.conList")});

>> to handle various response states checked it with conditional statements and showed error if there are any.

I hope this helps and in case if this comes handy can you please choose this as best answer so that it can be useful for others in the future.

Let me know in case if there are any questions.
Raviteja_KRaviteja_K

Hi

Just update your parameter name in the apex controller as shown below and try to execute the code.
   

public static void createContact( Contact ac
      

If your query is resolved please mark this as a best answer.