1

I can't seem to get the Id of my newly created Contact record. When clicking the "Save Contact" button, the contact is saved, but I can't figure out how to reference the new Id. I would like to use it to e.force:navigateToSObject

newHousehold.cmp

<aura:component implements="force:lightningQuickActionWithoutHeader,force:appHostable" controller="NewHouseholdController">

    <aura:attribute name="contacts" type="Contact[]"/>
    <aura:attribute name="newContact" type="Contact"
     default="{ 'sobjectType': 'Contact',
                    'FirstName': '',
                    'LastName': '',
                    'Title': '' }"/>

    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>

    <!-- PAGE HEADER -->
    <lightning:layout class="slds-page-header slds-page-header--object-home">
        <lightning:layoutItem >
            <lightning:icon iconName="standard:contact" alternativeText="New Household Contacts"/>
        </lightning:layoutItem>
        <lightning:layoutItem padding="horizontal-small">
            <div class="page-section page-header">
                <h1 class="slds-text-heading--label">Contacts</h1>
                <h2 class="slds-text-heading--medium">New Household Contacts</h2>
            </div>
        </lightning:layoutItem>
    </lightning:layout>
    <!-- / PAGE HEADER -->

    <!-- FORM -->
    <lightning:layout >
        <lightning:layoutItem padding="around-small" size="12">

            <div aria-labelledby="newcontactform" aura:id="primaryDiv">

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

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

                    <form class="slds-form--stacked">
                        <lightning:input aura:id="contactform" name="firstname" label="First Name"
                                         value="{!v.newContact.FirstName}" required="true"/>

                        <lightning:input aura:id="contactform" name="lastname" label="Last Name"
                                         value="{!v.newContact.LastName}" required="true"/>

                        <lightning:input aura:id="contactform" name="title" label="Title"
                                         value="{!v.newContact.Title}" />

                        <div class="slds-clearfix">
                            <div class="slds-float_left">
                                <lightning:button label="Save and Add Spouse" onclick="{!c.openAddSpouse}"
                                          variant="brand" class="slds-m-top--medium"/>
                                <lightning:button label="Cancel" onclick="{!c.cancelButton}"
                                          variant="brand" class="slds-m-top--medium"/>
                            </div>
                            <div class="slds-float_right">
                                <lightning:button label="Save Contact" onclick="{!c.clickCreate}"
                                          variant="brand" class="slds-m-top--medium"/>
                            </div>
                        </div>

                    </form>

                </fieldset>
                <!-- / BOXED AREA -->
            </div>
        </lightning:layoutItem>
    </lightning:layout>
    <!-- / FORM -->

    <!-- Initially hidden spouse add form -->
    <div aura:id="spouseDiv" class="slds-hide">
        <c:addSpouse />
    </div>
    <!-- / Initially hidden spouse add form -->

    <!-- Display list of contacts 
    <c:contactsList contacts="{!v.contacts}"/> -->

</aura:component>

newHouseholdController.js

({
    // Load contacts from Salesforce
    doInit: function(component, event, helper) {

        // Create the action
        var action = component.get("c.getContacts");

        // Add callback behavior for when response is received
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.contacts", response.getReturnValue());
            }
            else {
                console.log("Failed with state: " + state);
            }
        });

        // Send action off to be executed
        $A.enqueueAction(action);
    },

    clickCreate: function(component, event, helper) {
        //console.log("inside clickCreate");
        var validContact = component.find('contactform').reduce(function (validSoFar, inputCmp) {
            // Displays error messages for invalid fields
            inputCmp.showHelpMessageIfInvalid();
            return validSoFar && inputCmp.get('v.validity').valid;
        }, true);
        // If we pass error checking, do some real work
        if(validContact){
            // Create the new contact
            var newContact = component.get("v.newContact");
            console.log("Create contact: " + JSON.stringify(newContact));

            helper.createContact(component, newContact);
            // 11/6/17 having trouble here
            console.log(newContact.Id);

            // Close form window
            $A.get("e.force:closeQuickAction").fire();
        }
    },

    openAddSpouse: function(component, event, helper) {
        var validContact = component.find('contactform').reduce(function (validSoFar, inputCmp) {
            // Displays error messages for invalid fields
            inputCmp.showHelpMessageIfInvalid();
            return validSoFar && inputCmp.get('v.validity').valid;
        }, true);
        // If we pass error checking, do some real work
        if(validContact){
            // Create the new contact
            var newContact = component.get("v.newContact");
            console.log("Create contact: " + JSON.stringify(newContact));
            helper.createContact(component, newContact);
        }

        // toggle to hide primary contact fields
        var divId = component.find('primaryDiv');
        $A.util.toggleClass(divId, 'slds-hide');

        // toggle to show spouse fields
        var divId = component.find('spouseDiv');
        $A.util.toggleClass(divId, 'slds-hide');
    },

        cancelButton: function(component, event, helper) {
        $A.get("e.force:closeQuickAction").fire();
    },

})

newHouseholdHelper.js

({
    createContact: function(component, contact) {
        var action = component.get("c.saveContact");
        action.setParams({"contact": contact});
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                var contacts = component.get("v.contacts");
                contacts.push(response.getReturnValue());
                component.set("v.contacts", contacts);
            }
        });
        $A.enqueueAction(action);
    },
})

NewHouseholdController.apxc

public with sharing class NewHouseholdController {

    @AuraEnabled
    public static List<Contact> getContacts() {

        // Check to make sure all fields are accessible to this user
        String[] fieldsToCheck = new String[] {
            'Id', 'FirstName', 'Last Name', 'Title'};

        Map<String,Schema.SObjectField> fieldDescribeTokens = 
        Schema.SObjectType.Contact.fields.getMap();

        for(String field : fieldsToCheck) {
            if( ! fieldDescribeTokens.get(field).getDescribe().isAccessible()) {
                throw new System.NoAccessException();
                return null;
            }
        }

        // OK, they're cool, let 'em through
        return [SELECT Id, FirstName, LastName, Title
                FROM Contact];
    }

    @AuraEnabled
    public static Contact saveContact(Contact contact) {
        // Perform isUpdatable() checking first, then
        insert contact;
        return contact;
    }

}
  • did you tried contact.id instead of contact.Id in js? – Manjot Singh Nov 11 '17 at 3:55
  • Have you tried using console.log to see what is being returned in your createContact method on your helper.js? What is it returning? – Renato Oliveira Nov 11 '17 at 11:36
  • Yes, I tried both .Id and .id. The console.log output is "undefined". – Navigatrix Nov 13 '17 at 15:56
1

I discovered the problem was actually in the fact that I am calling my saveContact method from inside an action (createContact). The action goes off and saves my contact but the rest of the program moves on and the id isn't set in time. The solution was to put the code that needed to use the id inside the action. Then I was able to access the id without an issue.

  • How can people know about where you are using the id unless you post the original area of the code. – Junaid P Khader Nov 17 '17 at 4:57
  • I posted all my code. I was using the id in newHouseholdController.js where is says "11/6/17 having trouble here". Using the id needed to be moved to the action in newHouseholdHelper.js – Navigatrix Nov 20 '17 at 16:30
0

The method u used is supposed to get the return. However try returning id of the contact from the apex controller. So the method becomes

@AuraEnabled
public static Id saveContact(Contact contact) {
    insert contact;
    return contact.Id;
}

Hope this helps.

  • Thanks everyone for your responses. It really helps to have things to try. I believe the problem actually lies in the fact that I am calling my saveContact method from an action (createContact). The action goes off and saves my contact but the rest of the program moves on and the id isn't set in time. Now do I have to put all the rest if my program in the action? It seems like there should be a better way. Can I have the controller wait for a the response from the action? – Navigatrix Nov 15 '17 at 16:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.