0

On my Custom input lightning component, I am pre-populating latest record field values. I have a submit button at the end of the form, clicking on it should create a new record with what ever input field values on each field.

Apex controller class:

//Fetching the latest record on to the Form
@AuraEnabled
public static Situation_and_Resource__c getLatestRec(){
    User runningUser = [Select Id, Contact.Id From User Where Id =: UserInfo.getUserId()];
    return [Select Field1__c, Field2__c,
                From CustomObject__c 
                WHERE CreatedBy.Id =: runningUser.Id 
                Order By CreatedDate DESC Limit 1 ];
}

//Creating a new record
@AuraEnabled
public static CustomObject__c createRec(CustomObject__c strsRecord){
    try{ 
        System.debug('StrsRecord:' +strsRecord);
        if(strsRecord != null){
            System.debug('Inside:' +strsRecord);
            insert strsRecord;
        }  
    }catch (Exception ex){

    }
    return strsRecord;
}

Lightning.cmp

<aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
<aura:attribute name="newRecord" type="CustomObject__c"
                default="{'sobjectType' : 'CustomObject__c' }"/>
 ...
 ...
  <lightning:button label="Submit" class="slds-m-top--medium"
                                      variant="brand"
                                      onclick="{!c.clickCreate}"/>
 ...
 ...

Lightning.JS

 doInit: function(component, event, helper) {


    //Fetching the latest record
    var action = component.get("c.getLatestRec");
    action.setCallback(this, function(response) {
        var state = response.getState();
        if (state === "SUCCESS") {
            component.set("v.newRecord", response.getReturnValue());
        }
        else {
            console.log("Failed with state: " + state);
        }
    });
    $A.enqueueAction(action);
},


 clickCreate: function(component, event, helper){
    var newJSRecord = component.get("v.newRecord");

    //Creating a new record on the button click
    var action = component.get("c.createRec");
    action.setParams({
        "strsRecord" : newJSRecord
    });
    action.setCallback(this, function(response){
        var state = response.getState();
        if (state === "SUCCESS") {

            //newRecord.push(response.getReturnValue());
            //component.set("v.newRecord", newRecord);
            alert('Record is Created Successfully');
        }else {
            alert('Error in calling server side action');
        }
    });
    $A.enqueueAction(action);
}

I am not able to create a new record. Am I missing something here?

  • 2
    what do you get in your catch block in the createRec method? – Jason Benkert Sep 7 '17 at 16:36
  • You typically have to JSON.stringify() the object before you pass it to Apex. Then in Apex, JSON.deserialize() the string back into the sObject. – Jason Benkert Sep 7 '17 at 16:37
  • Oh yeah, I just found the error from Catch block: 'System.DmlException: Insert failed. First exception on row 0 with id a0lr00000003KqOSSW; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]'. As per my understanding, I am not specifying any Id while I am inserting. – Arnold Jr. Sep 7 '17 at 16:42
  • what does System.debug('StrsRecord:' +strsRecord); show you? – Jason Benkert Sep 7 '17 at 16:46
  • Well, that getting me the right field values which are on the form. ALSO it includes the Id field of the latest record I fetched into the form. May be this id field is causing all the chaos for me. How to overcome this? – Arnold Jr. Sep 7 '17 at 16:49
2

In your javascript controller, make a copy of the record and remove the Id attribute. Then send that back to Apex for the insert.

var newJSRecord = component.get("v.newRecord");
var copy = newJSRecord;
delete copy.Id;

then

action.setParams({
    "strsRecord" : JSON.stringify(copy)
});

And in Apex, do this:

public static CustomObject__c createRec(String str){
    CustomObject__c strsRecord = (CustomObject__c)JSON.deserialize(str,CustomObject__c.class);

then insert the strsRecord custom object.

  • Well, this takes me to the error alert from the JS's state != Success : Error in calling server side action – Arnold Jr. Sep 7 '17 at 17:15
  • This didn't worked/helped. I am not sure why my server side method createRec is not being executed. – Arnold Jr. Sep 7 '17 at 17:45
  • ok, then you need to JSON.stringify the object. I'll update the answer. – Jason Benkert Sep 7 '17 at 18:39
  • I don't think JSON.stringify has anything to do here, as my code works in sending all field information from JS to Apex with ID field initially. BTW I figured out the issue tho. I will post it as an answer. – Arnold Jr. Sep 7 '17 at 19:03
0

With the help of @JasonBenkert I was able to identify the actual issue, i.e, Id being passed when I try to insert new record. Along with this, one more hidden issue was: In the JS function that fetches the latest record, I need to explicitly provide the sobjectType to the response as its being lost whenever I try to insert a new record.

action.setCallback(this, function(response) {
        var state = response.getState();
        if (state == "SUCCESS") {
            var newRecord = response.getReturnValue();
            newRecord.sobjectType = 'CustomObject__c';
            component.set("v.newRecord", newRecord); 
        }
        else {
            console.log("Failed with state: " + state);
        }
    });

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.