instantiate a new sobject record in lightning controller
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 '';
}
}