Skip to content

Instantly share code, notes, and snippets.

@sohalloran
Last active May 1, 2018 14:26
Show Gist options
  • Select an option

  • Save sohalloran/454f1eddbe6b58336195b7455d66d33f to your computer and use it in GitHub Desktop.

Select an option

Save sohalloran/454f1eddbe6b58336195b7455d66d33f to your computer and use it in GitHub Desktop.
Reuseable Lightning Data Service Component
<aura:component extends="c:DataSvc" controller="AccountsListController">
<aura:attribute name="rows" type="Object[]" description="The row data."/>
<aura:attribute name="columns" type="List" default="[{label:'Id', fieldName: 'Id', type: 'text'},{label:'Name', fieldName: 'Name', type: 'text'}]"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<lightning:datatable data="{!v.rows}" keyField="Id" columns="{!v.columns}"/>
</aura:component>
//CONTROLLER
({
doInit : function(component, event, helper) {
helper.callServer(component,"c.getAccounts",function(response){
component.set("v.rows", response);
},'',true);
}
})
<aura:application extends="force:slds">
<c:AccountsList/>
</aura:application>
public with sharing class AccountsListController {
@AuraEnabled
public static List<Account> getAccounts() {
return [
SELECT Id, Name
from Account
order by Name
];
}
}
<aura:component abstract="true" extensible="true">
{!v.body}
</aura:component>
//HELPER
({
callServer : function(component,method,callback,params,isStoreable) {
var action = component.get(method);
if(isStoreable) {
action.setStorable();
}
if (params) {
action.setParams(params);
}
action.setCallback(this,function(response) {
var state = response.getState();
if (state === "SUCCESS") {
// pass returned value to callback function
callback.call(this,response.getReturnValue());
} else if (state === "ERROR") {
// generic error handler
var errors = response.getError();
if (errors) {
console.log("Errors", errors);
if (errors[0] && errors[0].message) {
throw new Error("Error" + errors[0].message);
}
} else {
throw new Error("Unknown Error");
}
}
});
$A.enqueueAction(action);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment