[SalesForce] instantiate a new sobject record in lightning controller

I havent been able to find any sample js that clearly describes how to instantiate a new sobject from within a lightning component. Lets say I want to create a list of new custom sobjects named foo (that only have a name field) to pass into my server side controller for final DML – any ideas ?

I assume I would
have an aura:attribute on my component of name = fooList and type ='foo[]'.
Then from within my controller.js I would do a fooList = component.get("v.fooList")
but how do I then define a new sobject of type foo with name set, and push in instances of the sobject foo into fooList?

Any insights would be most appreciated.

Best Answer

You can certainly create a sobject instance in client and pass as it as array from the component and retrieve it as List<sObject> in the controller.

If you want to pass a specific sObject type you, have to set the sobjectType.

For eg: sobjectType to Account

Here an simple example to do it.

TestApp:

<aura:application controller="AccountController" access="public">
    <aura:attribute name="accounts" type="List" access="private"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

    <aura:iteration items="{!v.accounts}" var="acc">
        <ui:inputText value="{!acc.Name}"/><br/>
    </aura:iteration>

    <ui:button press="{!c.saveAcc}" label="Save"/>
</aura:application>

TestAppController.js

({
    doInit : function(cmp, event, helper) {
        var acc = [];

        for(var i = 0;i < 5;i++){
            //set sobjectType to Account, if account is passed
            acc.push({'sobjectType':'Account','Name':'Test'+i});
        }

        cmp.set("v.accounts",acc);

    },
    saveAcc : function(cmp, event, helper) {

        var action = cmp.get("c.insertAccounts");
        action.setParams({
            "acc":cmp.get("v.accounts")
        });

        actions.setCallback(this,function(resp){

            var state = resp.getState();

            if(state === 'SUCCESS'){
                console.log(resp.getReturnValue());
            }
            else if(state === 'ERROR'){
                var errors = resp.getError();
                for(var i = 0 ;i < errors.length;i++){
                    console.log(errors[i].message);
                }
            }

        });

        $A.enqueueAction(action);

    }
})

Apex Controller:

public with sharing class AccountController {

    //if sobject is specific for eg:Account,then you use List<Account> acc
    @AuraEnabled
    public static String insertAccounts(List<sObject> acc){
        try{
            insert acc;
            System.debug('acc'+acc);
            return 'success';
        }
        catch(DMLException ex){
           AuraHandledException e = new AuraHandledException(ex.getMessage());
           throw e;
        }
        return '';        
    }
}