Salesforce Lightning组件开发一个简单的待办事项列表
大家好! 今天我们学习怎么使用Salesforce Ligthning 组件和自定义对象创建一个很简单的自定义任务列表,看好喽!!!
- 首先,我们必须创建一个对象,还有几个自定义的字段
资源 | 名称 |
---|---|
自定义对象 | ToDo |
资源 | 名称 |
---|---|
自定义字段 | Description |
Due_Date | |
Reminder_Date | |
Name |
- 编写
apex
控制器,打开我们的控制台,进行开发 ToDoController
复制一下代码:
public with sharing class ToDoController {
//方法,以在组件初始化期间返回toDo记录的列表
@AuraEnabled
public static List<ToDo__c> loadData(){
return [SELECT ID,Reminder_Date__c,Due_Date__c,Description__c FROM ToDo__c ORDER BY Due_Date__c ASC NULLS LAST];
}
//方法将记录保存到数据库中并返回错误消息
@AuraEnabled
public static String saveTodoRecord(ToDo__c toDoRecord){
String message;
Database.saveResult sr = Database.insert(toDoRecord,false);
if(!sr.isSuccess()){
for(Database.error err : sr.getErrors()){
message += err.getMessage();
}
}
return message;
}
}
Lightning Component
复制以下代码:
<aura:component controller="ToDoController" implements="flexiPage:availableForAllPageTypes">
<!--Componnet init handler -->
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<!--AURA ATTRIBUTES START-->
<aura:attribute name="todocolumns" type="List"/>
<aura:attribute name="todoData" type="Object"/>
<aura:attribute name="today" type="Date" description="To set todays date as mimimum value for Due date and reminder date"/>
<aura:attribute name="objToDo" type="ToDo__c" default="{'sobjectType' : 'ToDo__c'}"/>
<!--AURA ATTRIBUTES END-->
<!--TO DO Form START-->
<lightning:card title="Add New Task">
<aura:set attribute="actions">
<lightning:buttonicon iconName="utility:chevrondown" alternativeText="down icon" onclick="{!c.toggleForm}"/>
</aura:set>
<div aura:id="formDiv" class="slds-size_1-of-1 slds-p-around_medium">
<lightning:textarea aura:id="todoForm"
type="String"
label="Task Description"
value="{!v.objToDo.Description__c}"
required="true"
messageWhenValueMissing="Enter description" />
<lightning:input aura:id="todoForm"
type="Date"
label="Due date"
value="{!v.objToDo.Due_Date__c}"
required="true"
messageWhenValueMissing="Enter due date"
min="{!v.today}"
onchange="{!c.setMaxValueOfReminderDate}"/>
<lightning:input aura:id="reminderDate"
type="Date"
disabled="true"
label="Reminder date"
value="{!v.objToDo.Reminder_Date__c}"
min="{!v.today}"/>
<lightning:button class="slds-m-top_small"
label="Create Task"
variant="brand"
onclick="{!c.saveTodo}"/>
</div>
</lightning:card>
<!--TO DO Form END-->
<div class="slds-m-vertical_large">
<!--Lightning data table definition to display all To-Do Tasks-->
<lightning:datatable aura:id="tableId"
keyField="Id"
columns="{!v.todocolumns}"
data="{!v.todoData}"
hideCheckboxColumn="true"/>
</div>
</aura:component>
JS控制器
复制以下代码:
({
//方法设置数据表的列和数据
doInit : function(component,event,helper){
// create current date instance
var now = new Date();
var date = now.getDate();
var month = now.getMonth() + 1;
var fullYear = now.getFullYear();
var today = fullYear + '-' + month + '-' + date;
component.set("v.today", today);
// 设置闪电数据列
component.set("v.todocolumns",[
{
label:'Description',
fieldName : 'linkToRecord',
type:'url',
typeAttributes:{label:{fieldName:'Description__c'},target:'_blank'}//to display link to record page
},
{
label :'Due Date',
fieldName:'Due_Date__c',
type:'date',
typeAttributes:{day:'2-digit',month:'long',year:'2-digit'}
},
{
label:'Reminder Date',
fieldName:'Reminder_Date__c',
type:'date',
typeAttributes:{day:'2-digit',month:'long',year:'2-digit'}
}
]);
// 调用辅助函数来获取记录数据
helper.getData(component,event,helper);
},
toggleForm : function(component,event,helper){
//更改切换按钮图标
var evtSource = event.getSource();
if(evtSource.get("v.iconName") === 'utility:chevrondown'){
evtSource.set("v.iconName" , 'utility:chevronright' );
}else{
evtSource.set("v.iconName" , 'utility:chevrondown' );
}
//显示/隐藏表单元素
$A.util.toggleClass(component.find("formDiv"),'slds-hide');
},
saveTodo : function(component,event,helper){
//如果表单数据有效,则将记录保存在数据库中
if(helper.validateData(component,event,helper)){
//在datatable中附加新的todo条目
var objToDo = component.get("v.objToDo");
//调用saveTodoRecord服务器端方法来保存todo记录
var action = component.get("c.saveTodoRecord");
action.setParams({
toDoRecord : objToDo
});
action.setCallback(this,function(response){
var state = response.getState();
if(state == "SUCCESS"){
var toastRef = $A.get("e.force:showToast");
if(response.getReturnValue() == null){
toastRef.setParams({
"type" : "Success",
"title" : "Success",
"message" : "New Task is Created.",
"mode" : "dismissible"
});
}
else{
toastRef.setParams({
"type" : "Error",
"title" : "Error",
"message" : response.getReturnValue(),
"mode" : "sticky"
});
}
toastRef.fire();
$A.get("e.force:refreshView").fire();
}
else{
//处理服务器错误
console.log('Error during saving '+state);
}
});
$A.enqueueAction(action);
}
},
setMaxValueOfReminderDate : function(component, event, helper){
var dueDate = event.getSource().get("v.value");
component.find("reminderDate").set("v.value",'');
//一旦到期日期被输入,提醒日期被启用
if(dueDate != null && dueDate != ''){
component.find("reminderDate").set("v.disabled",false);
//设置提醒日期的最大日期限制
component.find("reminderDate").set("v.max",dueDate);
}
else{
component.find("reminderDate").set("v.disabled",true);
}
}
})
JS Helper
复制以下代码块:
({
getData : function(component,event,helper){
//调用loadData服务器端方法获取toDo记录
var action = component.get("c.loadData");
action.setCallback(this,function(response){
var state = response.getState();
if(state == "SUCCESS"){
var dotoList = response.getReturnValue();
for(var i=0; i < dotoList.length;i++){
//将todo项的描述显示为链接
dotoList[i].linkToRecord = '/'+dotoList[i].Id;
}
component.set("v.todoData",dotoList);
}
else{
//处理服务器错误
console.log('Error occured while init of data '+state);
}
});
$A.enqueueAction(action);
},
validateData : function(component, event, helper){
var isValid = component.find("todoForm").reduce(function(validSoFar,inputComp){
//当用户保存包含无效数据的表单时显示错误消息
inputComp.showHelpMessageIfInvalid();
return validSoFar && inputComp.get("v.validity").valid;
},true);
return isValid;
}
})