Lightning Data ServiceはLightningコンポーネント開発で利用できる便利な機能です。VisualforceのStandardControllerと同じような感じでApexクラスを用意せずに値を取得したりできます。
レコードの読み込み
ldsDisplayRecord.cmp
<aura:component implements="flexipage:availableForRecordHome, force:hasRecordId"> <!--inherit recordId attribute--> <aura:attribute name="record" type="Object" description="The record object to be displayed"/> <aura:attribute name="simpleRecord" type="Object" description="A simplified view record object to be displayed"/> <aura:attribute name="recordError" type="String" description="An error message bound to force:recordData"/> <force:recordData aura:id="record" layoutType="FULL" recordId="{!v.recordId}" targetError="{!v.recordError}" targetRecord="{!v.record}" targetFields ="{!v.simpleRecord}" mode="VIEW"/> <!-- Display a header with details about the record --> <div class="slds-page-header" role="banner"> <p class="slds-text-heading--label">{!v.simpleRecord.Name}</p> <h1 class="slds-page-header__title slds-m-right--small lds-truncate slds-align-left">{!v.simpleRecord.BillingCity}, {!v.simpleRecord.BillingState}</h1> </div> <!-- Display Lightning Data Service errors, if any --> <aura:if isTrue="{!not(empty(v.recordError))}"> <div class="recordError"> <ui:message title="Error" severity="error" closable="true"> {!v.recordError} </ui:message> </div> </aura:if> </aura:component>
レコードの保存
ldsSaveRecord.cmp
<aura:component implements="flexipage:availableForRecordHome, force:hasRecordId"> <!--inherit recordId attribute--> <aura:attribute name="record" type="Object" /> <aura:attribute name="simpleRecord" type="Object" /> <aura:attribute name="recordError" type="String" /> <force:recordData aura:id="recordEditor" layoutType="FULL" recordId="{!v.recordId}" targetError="{!v.recordError}" targetRecord="{!v.record}" targetFields ="{!v.simpleRecord}" mode="EDIT" /> <!-- Display a header with details about the record --> <div class="slds-form--stacked"> <div class="slds-form-element"> <label class="slds-form-element__label" for="recordName">Name: </label> <div class="slds-form-element__control"> <ui:outputText class="slds-input" aura:id="recordName" value="{!v.simpleRecord.Name}"/> </div> </div> </div> <!-- Display Lightning Data Service errors, if any --> <aura:if isTrue="{!not(empty(v.recordError))}"> <div class="recordError"> <ui:message title="Error" severity="error" closable="true"> {!v.recordError} </ui:message> </div> </aura:if> <!-- Display an editing form --> <lightning:input aura:id="recordName" name="recordName" label="Name" value="{!v.simpleRecord.Name}" required="true"/> <lightning:button label="Save Record" onclick="{!c.handleSaveRecord}" variant="brand" class="slds-m-top--medium"/> </aura:component>
LdsSaveRecordController.js
({ handleSaveRecord: function(component, event, helper) { component.find("recordEditor").saveRecord($A.getCallback(function(saveResult) { if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") { console.log("Save completed successfully."); } else if (saveResult.state === "INCOMPLETE") { console.log("User is offline, device doesn't support drafts."); } else if (saveResult.state === "ERROR") { console.log('Problem saving record, error: ' + JSON.stringify(saveResult.error)); } else { console.log('Unknown problem, state: ' + saveResult.state + ', error: ' + JSON.stringify(saveResult.error)); } }));} })
レコードの作成
ldsNewRecord.cmp
<aura:component implements="flexipage:availableForRecordHome, force:hasRecordId"> <aura:attribute name="newContact" type="Object"/> <aura:attribute name="simpleNewContact" type="Object"/> <aura:attribute name="newContactError" type="String"/> <force:recordData aura:id="contactRecordCreator" layoutType="FULL" targetRecord="{!v.newContact}" targetFields ="{!v.simpleNewContact}" targetError="{!v.newContactError}" /> <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> <!-- Display a header --> <div class="slds-page-header" role="banner"> <p class="slds-text-heading--label">Create Contact</p> </div> <!-- Display Lightning Data Service errors --> <aura:if isTrue="{!not(empty(v.newContactError))}"> <div class="recordError"> <ui:message title="Error" severity="error" closable="true"> {!v.newContactError} </ui:message> </div> </aura:if> <!-- Display the new contact form --> <div class="slds-form--stacked"> <lightning:input aura:id="contactField" name="firstName" label="First Name" value="{!v.simpleNewContact.FirstName}" required="true"/> <lightning:input aura:id="contactField" name="lastname" label="Last Name" value="{!v.simpleNewContact.LastName}" required="true"/> <lightning:input aura:id="contactField" name="title" label="Title" value="{!v.simpleNewContact.Title}" /> <lightning:button label="Save contact" onclick="{!c.handleSaveContact}" variant="brand" class="slds-m-top--medium"/> </div> </aura:component>
ldsNewRecordController.js
({ doInit: function(component, event, helper) { // Prepare a new record from template component.find("contactRecordCreator").getNewRecord( "Contact", // sObject type (entityAPIName) null, // recordTypeId false, // skip cache? $A.getCallback(function() { var rec = component.get("v.newContact"); var error = component.get("v.newContactError"); if(error || (rec === null)) { console.log("Error initializing record template: " + error); } else { console.log("Record template initialized: " + rec.sobjectType); } }) ); }, handleSaveContact: function(component, event, helper) { if(helper.validateContactForm(component)) { component.set("v.simpleNewContact.AccountId", component.get("v.recordId")); component.find("contactRecordCreator").saveRecord(function(saveResult) { if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") { // record is saved successfully var resultsToast = $A.get("e.force:showToast"); resultsToast.setParams({ "title": "Saved", "message": "The record was saved." }); resultsToast.fire(); } else if (saveResult.state === "INCOMPLETE") { // handle the incomplete state console.log("User is offline, device doesn't support drafts."); } else if (saveResult.state === "ERROR") { // handle the error state console.log('Problem saving contact, error: ' + JSON.stringify(saveResult.error)); } else { console.log('Unknown problem, state: ' + saveResult.state + ', error: ' + JSON.stringify(saveResult.error)); } }); } } })
レコードの削除
ldsDeleteRecord.cmp
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId"> <aura:attribute name="recordError" type="String" access="private"/> <force:recordData aura:id="recordHandler" recordId="{!v.recordId}" fields="Id" /> <!-- Display Lightning Data Service errors, if any --> <aura:if isTrue="{!not(empty(v.recordError))}"> <div class="recordError"> <ui:message title="Error" severity="error" closable="true"> {!v.recordError} </ui:message> </div> </aura:if> <!-- Display the delete record form --> <div class="slds-form-element"> <lightning:button label="Delete Record" onclick="{!c.handleDeleteRecord}" variant="brand" /> </div> </aura:component>
ldsDeleteRecordController.js ※エラーで動かず
({ handleDeleteRecord: function(component, event, helper) { component.find("recordHandler").deleteRecord($A.getCallback(function(deleteResult) { if (deleteResult.state === "SUCCESS" || deleteResult.state === "DRAFT") { console.log("Record is deleted."); } else if (deleteResult.state === "INCOMPLETE") { console.log("User is offline, device doesn't support drafts."); } else if (deleteResult.state === "ERROR") { console.log('Problem deleting record, error: ' + JSON.stringify(deleteResult.error)); } else { console.log('Unknown problem, state: ' + deleteResult.state + ', error: ' + JSON.stringify(deleteResult.error)); } })); })
非同期レコードの保存
Salesforce1アプリの場合は一時的にオフラインになった場合でも非同期で保存処理を実行する仕組みがあるそうです。
開発ドキュメント
実際に動くコード
上記の開発者ドキュメントページのサンプルコードに取引先責任者の保存機能がありましたので試してみました。
ldsQuickContact.cmp
<aura:component implements="force:lightningQuickActionWithoutHeader,force:hasRecordId"> <aura:attribute name="account" type="Object"/> <aura:attribute name="simpleAccount" type="Object"/> <aura:attribute name="accountError" type="String"/> <force:recordData aura:id="accountRecordLoader" recordId="{!v.recordId}" fields="Name,BillingCity,BillingState" targetRecord="{!v.account}" targetFields="{!v.simpleAccount}" targetError="{!v.accountError}" /> <aura:attribute name="newContact" type="Object" access="private"/> <aura:attribute name="simpleNewContact" type="Object" access="private"/> <aura:attribute name="newContactError" type="String" access="private"/> <force:recordData aura:id="contactRecordCreator" layoutType="FULL" targetRecord="{!v.newContact}" targetFields="{!v.simpleNewContact}" targetError="{!v.newContactError}" /> <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> <!-- Display a header with details about the account --> <div class="slds-page-header" role="banner"> <p class="slds-text-heading--label">{!v.simpleAccount.Name}</p> <h1 class="slds-page-header__title slds-m-right--small slds-truncate slds-align-left">Create New Contact</h1> </div> <!-- Display Lightning Data Service errors, if any --> <aura:if isTrue="{!not(empty(v.accountError))}"> <div class="recordError"> <ui:message title="Error" severity="error" closable="true"> {!v.accountError} </ui:message> </div> </aura:if> <aura:if isTrue="{!not(empty(v.newContactError))}"> <div class="recordError"> <ui:message title="Error" severity="error" closable="true"> {!v.newContactError} </ui:message> </div> </aura:if> <!-- Display the new contact form --> <lightning:input aura:id="contactField" name="firstName" label="First Name" value="{!v.simpleNewContact.FirstName}" required="true"/> <lightning:input aura:id="contactField" name="lastname" label="Last Name" value="{!v.simpleNewContact.LastName}" required="true"/> <lightning:input aura:id="contactField" name="title" label="Title" value="{!v.simpleNewContact.Title}" /> <lightning:input aura:id="contactField" type="phone" name="phone" label="Phone Number" pattern="^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$" messageWhenPatternMismatch="The phone number must contain 7, 10, or 11 digits. Hyphens are optional." value="{!v.simpleNewContact.Phone}" required="true"/> <lightning:input aura:id="contactField" type="email" name="email" label="Email" value="{!v.simpleNewContact.Email}" /> <lightning:button label="Cancel" onclick="{!c.handleCancel}" class="slds-m-top--medium" /> <lightning:button label="Save Contact" onclick="{!c.handleSaveContact}" variant="brand" class="slds-m-top--medium"/> </aura:component>
ldsQuickContactController.js
({ doInit: function(component, event, helper) { component.find("contactRecordCreator").getNewRecord( "Contact", // sObject type (entityApiName) null, // recordTypeId false, // skip cache? $A.getCallback(function() { var rec = component.get("v.newContact"); var error = component.get("v.newContactError"); if(error || (rec === null)) { console.log("Error initializing record template: " + error); } else { console.log("Record template initialized: " + rec.sobjectType); } }) ); }, handleSaveContact: function(component, event, helper) { if(helper.validateContactForm(component)) { component.set("v.simpleNewContact.AccountId", component.get("v.recordId")); component.find("contactRecordCreator").saveRecord(function(saveResult) { if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") { // Success! Prepare a toast UI message var resultsToast = $A.get("e.force:showToast"); resultsToast.setParams({ "title": "Contact Saved", "message": "The new contact was created." }); // Update the UI: close panel, show toast, refresh account page $A.get("e.force:closeQuickAction").fire(); resultsToast.fire(); // Reload the view so components not using force:recordData // are updated $A.get("e.force:refreshView").fire(); } else if (saveResult.state === "INCOMPLETE") { console.log("User is offline, device doesn't support drafts."); } else if (saveResult.state === "ERROR") { console.log('Problem saving contact, error: ' + JSON.stringify(saveResult.error)); } else { console.log('Unknown problem, state: ' + saveResult.state + ', error: ' + JSON.stringify(saveResult.error)); } }); } }, handleCancel: function(component, event, helper) { $A.get("e.force:closeQuickAction").fire(); }, })
ldsQuickContactHelper.js
({ validateContactForm: function(component) { var validContact = true; // Show error messages if required fields are blank var allValid = component.find('contactField').reduce(function (validFields, inputCmp) { inputCmp.showHelpMessageIfInvalid(); return validFields && inputCmp.get('v.validity').valid; }, true); if (allValid) { // Verify we have an account to attach it to var account = component.get("v.account"); if($A.util.isEmpty(account)) { validContact = false; console.log("Quick action context doesn't have a valid account."); } return(validContact); } } })
『force:lightningQuickActionWithoutHeader』が宣言されているので、クイックアクションで利用できます。
作成したアクションはページレイアウトで追加できます。
動かしてみたらエラーメッセージ。
アレっと思ってコードをちゃんと確認したら取引先のページに設置するためのコンポーネントでした。ということで、取引先アクションとして作り直して・・・
無事に動かすことができました。
保存処理もサクサク動きます。必須項目の値が未入力の場合は入力欄の下にリアルタイムでエラーコメントが表示されたりしました。
シンプルなLightningコンポーネントの開発なら少ない工数で実装を可能にしてくれそうです。