0

Am trying to save contact record with Account input in lightning component.

Component:

    <aura:component controller="addDeleteController" Implements="flexipage:availableForRecordHome,force:hasRecordId">

    <aura:attribute name="contact" type="Contact" 
                    default="{ 'sobjectType': 'Contact' }"/>
    <!--<aura:handler name="init" value="{!this}" action="{!c.doInit}" />-->
    <lightning:messages />
    <force:inputField value="{!v.contact.Name}"/>
    <force:inputField value="{!v.contact.AccountId}"/>
    <button class="slds-button slds-button_brand" onclick="{!c.Save}">Save</button>
</aura:component>

Controller.js

({
Save: function(component, event, helper) { 
    alert('inside save action');
    var action = component.get("c.saveSingleContact");
    console.log('-----'+component.get("v.contact"));
    action.setParams({
        "singleContact": component.get("v.contact")
    });
    // set call back 
    action.setCallback(this, function(response) {
        var state = response.getState();
        if (state === "SUCCESS") {
            // if response if success then reset/blank the 'contactList' Attribute 
            // and call the common helper method for create a default Object Data to Contact List 
            component.set("v.contact", []);
            alert('record Save');
        }
        else{
            alert('failed----'+response);
        }
    });
    // enqueue the server side action  
    $A.enqueueAction(action);
},

})

Apex:

    @AuraEnabled
public static void saveSingleContact(Contact singleContact){
    System.debug('##### '+singleContact);
    Insert singleContact;
}

In server side, am getting below error:

System.DmlException: Insert failed. First exception on row 0; first error: INVALID_FIELD, Cannot specify both an external ID reference Account and a salesforce id, AccountId: []

What am doing wrong?. Am trying to insert only one account with contact.

Thanks for help in advance!.

1 Answer 1

0

Okay, I found a solution.

I just added below line before inserting the Contact in the apex method

singleContact.Account = null;

Now my apex method is,

 @AuraEnabled
public static void saveSingleContact(Contact singleContact){
    System.debug('##### '+singleContact);
    singleContact.Account = null;
    Insert singleContact;
}

Debug -- singleContact|{"Account":{"Name":"United Oil & Gas Cor (2 more) ..."},"AccountId":"00128000006axmwAAA"}

Since it is already having AccountId in it, I nullified Account from the singleContact and it worked.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .