About

all about SFDC

Sunday, 10 December 2017

Salesforce Notes view VF Component

Salesforce Notes view VF Component

Hello geeks, This is about a SF Notes display in view only. Actually intended for a specific profile to display notes in View only in Detail Page Layout and removing standard related list and added a custom VF page in Detail section . I came across this scenario in one of my project and i hope it would be useful for someone. Used an  OFFSET based pagination since ContentNotes doesn't allow standardsetcontroller pagination. And also to display popup used a rerender based to make component simple as possible. Page: This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters <apex:page > <apex:form > <c:NotesComponent value="{!$CurrentPage.parameters.id}" /> <!-- 0019000001JKPqi --> </apex:form> </apex:page> view raw NotesPage.xml hosted with ❤ by GitHub VF Component: This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters <apex:component controller="NoteCompCntrlr" access="GLOBAL"> <apex:attribute name="value" access="GLOBAL" description="The parent record ID of the Notes" type="string" assignTo="{!selectedValue}"/> <apex:slds /> <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <script> $(document).ready(function () { doInitReviewPnl(); }); function doInitReviewPnl(){ $("a[id^=show_]").click(function(event) { $("#extra_" + $(this).attr('id').substr(5)).slideToggle("fast"); event.preventDefault(); }) } </script> <apex:outputpanel id="scriptPnl"> <script> doInitReviewPnl(); </script> </apex:outputpanel> <apex:outputpanel id="resPanel"> <!-- SEARCH RESULTS HEADER --> <div class="slds-page-header" role="banner"> <div class="slds-grid"> <div class="slds-col slds-has-flexi-truncate"> <!-- HEADING AREA --> <p class="slds-text-title--caps slds-line-height--reset"> <span class="slds-icon_container slds-icon-standard-record slds-icon--small" title="Account Standard Icon"> <img src="{!URLFOR($Asset.SLDS, 'assets/icons/standard/note_120.png')}" alt="Account Standard Icon" /> </span>&nbsp;&nbsp;Notes</p> <!-- / HEADING AREA --> </div> </div> </div> <!-- / SEARCH RESULTS HEADER --> <!-- SEARCH RESULTS TABLE --> <div class="slds-panel slds-grid slds-grid--vertical slds-nowrap"> <div class="slds-form--stacked slds-grow slds-scrollable--x"> <table id="theaddrs" class="slds-table slds-table--bordered slds-table--cell-buffer"> <thead> <tr class="slds-text-title--caps"> <th scope="col"> <div class="slds-truncate" title="Action">Action</div> </th> <th scope="col"> <div class="slds-truncate" title="Title">Title</div> </th> <th scope="col"> <div class="slds-truncate" title="Text Preview">Preview</div> </th> <th scope="col"> <div class="slds-truncate" title="Owner">Owner</div> </th> <th scope="col"> <div class="slds-truncate" title="Created">Created Date</div> </th> </tr> </thead> <tbody> <apex:repeat value="{!AllNotes}" var="noteObj"> <tr> <td scope="row" data-label="Opportunity Name"> <div class="slds-truncate" title="Edit"> <apex:commandLink action="{!showContent}" style="color: blue;" value="Show Content" id="idAgregar" rerender="popupArea,popupContent"> <apex:param name="crntRec" value="{!noteObj.cNote.Id}" assignTo="{!curentRecId}"/> </apex:commandLink> </div> </td> <td > <div class="slds-truncate" ><apex:outputField value="{!noteObj.cNote.Title}"/></div> </td> <td > <a href="#" id="show_{!noteObj.cNote.Id}"><apex:outputField value="{!noteObj.cNote.TextPreview}"/></a> <div id="extra_{!noteObj.cNote.Id}" style="display: none;"> <apex:outputField value="{!noteObj.cNote.TextPreview}"/> </div> <!-- <div class="slds-truncate" ><apex:outputField value="{!noteObj.cNote.TextPreview}"/></div> --> </td> <td > <div class="slds-truncate" ><apex:outputField value="{!noteObj.cNote.owner.name}"/></div> </td> <td > <div class="slds-truncate" ><apex:outputField value="{!noteObj.cNote.CreatedDate}"/></div> </td> </tr> </apex:repeat> </tbody> </table> <br/><br/> <div class="slds-box slds-box--small slds-theme--shade slds-text-align--left"> <div class="slds-align_absolute-center"> <apex:commandButton styleclass="slds-button slds-button--neutral" value="First" status="pageStatus1" reRender="resPanel,scriptPnl" action="{!beginning}" disabled="{!prev}" title="First Page"/> <apex:commandButton styleclass="slds-button slds-button--brand" value="Previous" status="pageStatus1" reRender="resPanel,scriptPnl" action="{!previous}" disabled="{!prev}" title="Previous Page"/> <apex:commandButton styleclass="slds-button slds-button--brand" value="Next" status="pageStatus1" reRender="resPanel,scriptPnl" action="{!next}" disabled="{!nxt}" title="Next Page"/> <apex:commandButton styleclass="slds-button slds-button--neutral" value="Last" status="pageStatus1" reRender="resPanel,scriptPnl" action="{!end}" disabled="{!nxt}" /> &nbsp;&nbsp; <apex:actionStatus id="pageStatus1"> <apex:facet name="start"> <apex:outputPanel > &nbsp;&nbsp; <apex:image url="{!$Resource.loaderSmaill}" /> <apex:outputLabel /> </apex:outputPanel> </apex:facet> </apex:actionStatus> </div> </div> </div> </div> </apex:outputpanel> <apex:outputpanel id="popupArea"> <!--Use "slds-m-around- -xx-large" class to add standard Large padding to the component--> <div class="slds-m-around--xx-large"> <!--Use aura:if tag to display Model Box, on the bese of conditions. [isOpen boolean attribute] --> <apex:outputpanel id="popupContent" rendered="{!isOpen}"> <!--###### MODAL BOX Start From Here ######--> <div role="dialog" tabindex="-1" aria-labelledby="header99" class="slds-modal slds-fade-in-open "> <div class="slds-modal__container"> <!-- ###### MODAL BOX HEADER Part Start From Here ######--> <div class="slds-modal__header"> <button class="slds-button slds-modal__close slds-button--icon-inverse" title="Close" onclick="closeModel();return false;"> X <span class="slds-assistive-text">Close</span> </button> <h2 id="header99" class="slds-text-heading--medium">{!curentRec.Title}</h2> </div> <!--###### MODAL BOX BODY Part Start From Here ######--> <div class="slds-modal__content slds-p-around--medium"> <p><b><apex:outputtext value="{!fullContent}" escape="false"/> </b> </p> </div> <!--###### MODAL BOX FOOTER Part Start From Here ######--> <div class="slds-modal__footer"> <button class="slds-button slds-button--brand" onclick="closeModel();return false;">Cancel</button> </div> </div> </div> <div class="slds-backdrop slds-backdrop--open"></div> <!--###### MODAL BOX Part END Here ######--> </apex:outputpanel> </div> </apex:outputpanel> <apex:actionfunction name="closeModel" action="{!closeAction}" rerender="popupArea,popupContent" /> </apex:component> view raw NotesComp.xml hosted with ❤ by GitHub Apex Cls: This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters public class NoteCompCntrlr { public String soql; public String option {get;set;} public String lsourceoption {get;set;} public integer totalRecs {get;set;} private integer index = 0; private integer blockSize = 5; private list<string> cDocIds; public string curentRecId{get;set;} public boolean isOpen{get;set;} public string fullContent{get;set;} public contentNote curentRec{get;set;} public string RecIdParent{get;set;} public String selectedValue { get; set { selectedValue = value; if(string.isNotBlank(selectedValue)){ RecIdParent = selectedValue; initContentDocs(); } } } public NoteCompCntrlr() { system.debug('--selectedValue -- '+selectedValue ); isOpen = false; curentRecId = ''; fullContent =''; } private void initContentDocs(){ if(cDocIds==null){ cDocIds = new list<string>(); list<contentNote> totalNotes = new list<contentNote>(); if(string.isNotBlank(RecIdParent)){ for(ContentDocumentLink CLink : [ select ContentDocumentId from ContentDocumentLink where LinkedEntityId =: RecIdParent] ){ cDocIds.add(CLink.ContentDocumentId); } String qryStr = 'select id,CreatedDate,FileExtension,FileType,owner.name,Title,TextPreview from contentNote where Id IN: cDocIds AND FileType=\'SNOTE\''; totalNotes = Database.Query(qryStr); } totalRecs = totalNotes.size()>0 ? totalNotes.size() : 0; } } public List<contentWrap> getAllNotes() { list<contentWrap> cNotes = new list<contentWrap>(); if(cDocIds==null ){ initContentDocs(); } String qryStr = 'select id,Content,CreatedDate,FileExtension,FileType,owner.name,Title,TextPreview from contentNote where Id IN: cDocIds AND FileType=\'SNOTE\''; qryStr+= ' LIMIT ' + blockSize + ' OFFSET ' + index; for(contentNote cntNote : Database.Query(qryStr)){ contentWrap tempNote = new contentWrap(); tempNote.txtForm = ''; tempNote.cNote = cntNote; cNotes.add(tempNote); } return cNotes; } public List<SelectOption> getROptions() { List<SelectOption> rOptions = new List<SelectOption>(); rOptions.add(new SelectOption('None','-None-')); Schema.DescribeFieldResult fieldResult = Lead.Rating.getDescribe(); List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues(); for( Schema.PicklistEntry f : ple) { rOptions.add(new SelectOption(f.getLabel(), f.getValue())); } return rOptions; } public void beginning() { index = 0; } public void previous() { index = index - blockSize; } public void next() { index = index + blockSize; } public void end() { index = totalrecs - math.mod(totalRecs,blockSize); } public boolean getprev() { if(index == 0) return true; else return false; } public boolean getnxt() { if((index + blockSize) >= totalRecs) return true; else return false; } public class contentWrap { public string txtForm{get;set;} public contentNote cNote{get;set;} } public void showContent(){ system.debug('--curentRecId-- '+curentRecId); if(string.isNotBlank(curentRecId)){ list<contentNote> noteList = [select id,Content,title from ContentNote where id=: curentRecId]; curentRec = noteList.size()>0 ? noteList[0] : new contentNote(); isOpen = curentRec.Id!=null; fullContent = ''; if(isOpen){ fullContent = curentRec.Content.toString(); } system.debug('fullContent-- '+fullContent); system.debug('---curentRec--- '+curentRec); } } public void closeAction(){ isOpen = false; } } view raw NoteCompCntrlr.java hosted with ❤ by GitHub...

Saturday, 9 December 2017

Salesforce Lightning Compent to Insert Multiple Attachments

Salesforce Lightning Compent to Insert Multiple Attachments

Hello there. This is about a Lighting Component for uploading multiple Attachments for any Object. It would work for all objects and can also be re usable in SF communities. To get an easy understanding i've used the component in Quick Action / lightning action. Thanks to Manoj for actual idea and support. The Attachment would be inserted simultaneously  when selected a file and also deleteing would deleted from database. Component: This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters <aura:component implements="force:hasRecordId,force:lightningQuickActionWithoutHeader" controller="AttachmentUploadCon"> <aura:attribute name="rows" type="List" default="[]" /> <aura:attribute name="objAPIName" type="string" default="Account" access="GLOBAL"/> <aura:attribute name="RecID" type="string" access="GLOBAL"/> <aura:handler name="init" value="{!this}" action="{!c.initComp}"/> <div style="width:100%;"> <div style="float:left;width:70%;font-size: 20px;"><b>Upload Attachments</b></div> <div style="float:left;width:30%;text-align:center;"><lightning:button iconPosition="left" iconName="action:new" variant="brand" onclick="{!c.addRow}" /></div> <div style="clear:both;"></div> </div> <style> .slds-modal__container{max-width: 55rem !important;width:75%;} </style> <div style="overflow-y:auto;height:440px;" > <table class="slds-table slds-table_bordered slds-table_cell-buffer" style="margin: 2% auto;border: 1px solid #ddd;"> <tbody> <aura:iteration items="{!v.rows}" var="row"> <tr> <td scope="row" data-label="Row Number"> {!row.rowNum}. </td> <td data-label="Attachment"> <lightning:input class="{!row.rowNum - 1}" aura:id="fileId" onchange="{!c.handleFilesChange}" type="file" name="{!row.fileId}" label=" " multiple="false"/> {!row.fileName} <!--use aura:if for show-hide the loading spinner image--> </td> <td data-label="Action" class="slds-align_absolute-center action-col"> <aura:if isTrue="{!row.showLoadingSpinner}"> <div style="position: absolute;margin-left: -38%;" class="slds-text-body_small slds-text-color_error"> <img src="/auraFW/resources/aura/images/spinner.gif" class="spinner-img" alt="Loading"/>' </div> </aura:if> <lightning:button iconPosition="left" iconName="action:delete" variant="destructive" name="{!row.rowNum - 1}" class="{!'atcID_'+row.fileId}" onclick="{!c.deleteRow}" /> </td> </tr> </aura:iteration> </tbody> </table> </div> </aura:component> view raw MultiFileComp.xml hosted with ❤ by GitHub Controller JS: This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters ({ initComp: function(component, event, helper) { helper.getAttachments(component, event); }, deleteRow: function(component, event, helper) { var index = event.getSource().get('v.name'); var clsName = event.getSource().get('v.class'); console.log('recId@ delete', clsName.split('atcID_')); var clasAray = !$A.util.isEmpty(clsName) ? clsName.split('atcID_') : []; var recId = !$A.util.isEmpty(clasAray) ? clasAray[1] : ''; if(!$A.util.isEmpty(recId)) { var action = component.get("c.deleteAttachment"); action.setParams({"attchId": recId}); action.setCallback(this, function(response) { var state = response.getState(); console.log('state..!',state); if (state === "SUCCESS"){ helper.getAttachments(component, event); } else { alert('Something went wrong.'); } }); $A.enqueueAction(action); } }, clearError : function(component, event, helper) { var rows = component.get('v.rows'); var rowIndex = event.getSource().get("v.labelClass"); rows[rowIndex].cDocError = ''; component.set('v.rows',rows); }, handleFilesChange: function(component, event, helper) { //alert(); if (event.getSource().get("v.files").length > 0) { console.log('---@handleFilesChange---'); helper.uploadHelper(component, event); } }, addRow : function(component, event, helper) { var rows = component.get("v.rows"); var newRow = rows.length+1; rows.push({'rowNum':rows.length+1,'fileId':'','cDocError':'','parentId':'','fileName':'No File Selected..','showLoadingSpinner':false}); component.set("v.rows",rows); } }) view raw MultiFileComp_Cntrlr.js hosted with ❤ by GitHub Helper JS: This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters ({ MAX_FILE_SIZE: 4500000, //Max file size 4.5 MB CHUNK_SIZE: 750000, //Chunk Max size 750Kb uploadHelper: function(component, event) { // start/show the loading spinner // get the selected files using aura:id [return array of files] var rowIndex = event.getSource().get('v.class'); var attachmentId = event.getSource().get('v.name'); var rows = component.get('v.rows'); rows[rowIndex].showLoadingSpinner = true; component.set('v.rows',rows); var fileInput; if(typeof component.find("fileId")[rowIndex] == 'undefined') fileInput = component.find("fileId").get("v.files"); else fileInput = component.find("fileId")[rowIndex].get("v.files"); // get the first file using array index[0] var file = fileInput[0]; var self = this; var parentId = rows[rowIndex].parentId; // check the selected file size, if select file size greter then MAX_FILE_SIZE, // then show a alert msg to user,hide the loading spinner and return from function if (file.size > self.MAX_FILE_SIZE) { console.log('size exceeded.'); rows[rowIndex].showLoadingSpinner = false; rows[rowIndex].fileName = 'Alert : File size cannot exceed ' + self.MAX_FILE_SIZE + ' bytes.\n' + ' Selected file size: ' + file.size; component.set('v.rows',rows); return; } // create a FileReader object var objFileReader = new FileReader(); // set onload function of FileReader object objFileReader.onload = $A.getCallback(function() { console.log('--@objFileReader.onload --'); var fileContents = objFileReader.result; var base64 = 'base64,'; var dataStart = fileContents.indexOf(base64) + base64.length; fileContents = fileContents.substring(dataStart); // call the uploadProcess method self.uploadProcess(component, file, fileContents,rowIndex,attachmentId,parentId); }); objFileReader.readAsDataURL(file); }, uploadProcess: function(component, file, fileContents,rowIndex,attachmentId,parentId) { // set a default size or startpostiton as 0 var startPosition = 0; // calculate the end size or endPostion using Math.min() function which is return the min. value var endPosition = Math.min(fileContents.length, startPosition + this.CHUNK_SIZE); // start with the initial chunk, and set the attachId(last parameter)is null in begin this.uploadInChunk(component, file, fileContents, startPosition, endPosition, '',rowIndex,attachmentId,parentId); }, uploadInChunk: function(component, file, fileContents, startPosition, endPosition, attachId,rowIndex,attachmentId,parentId) { console.log('--@uploadInChunk---'); // call the apex method 'saveChunk' var getchunk = fileContents.substring(startPosition, endPosition); var action = component.get("c.saveChunk"); action.setParams({ parnttId: component.get("v.recordId"), attachmentName: file.name, attachmentBody: encodeURIComponent(getchunk), attachmentType: file.type, fileId: attachId, attachmentId:attachmentId }); // set call back action.setCallback(this, function(response) { console.log('--@uploadInChunk- setCallback--'); // store the response / Attachment Id attachId = response.getReturnValue(); var state = response.getState(); if (state === "SUCCESS") { console.log('--@uploadInChunk- success!!'); // update the start position with end postion startPosition = endPosition; endPosition = Math.min(fileContents.length, startPosition + this.CHUNK_SIZE); // check if the start postion is still less then end postion // then call again 'uploadInChunk' method , // else, diaply alert msg and hide the loading spinner if (startPosition < endPosition) { this.uploadInChunk(component, file, fileContents, startPosition, endPosition, attachId,rowIndex); } else { var rows = component.get('v.rows'); rows[rowIndex].showLoadingSpinner = false; rows[rowIndex].fileName = file.name; rows[rowIndex].fileId = attachId; component.set('v.rows',rows); //alert('your File is uploaded successfully'); this.getAttachments(component, event); } // handel the response errors } else if (state === "INCOMPLETE") { alert("From server: " + response.getReturnValue()); } else if (state === "ERROR") { var errors = response.getError(); if (errors) { if (errors[0] && errors[0].message) { console.log("Error message: " + errors[0].message); } } else { console.log("Unknown error"); } } }); // enqueue the action $A.enqueueAction(action); }, getAttachments : function(component, event) { var action = component.get("c.loadAttachments"); var recID = !$A.util.isEmpty(component.get("v.recordId")) ? component.get("v.recordId") : component.get("v.RecID"); action.setParams({ parentId: recID, sobjAPIName: component.get("v.objAPIName"), }); action.setCallback(this, function(response) { var state = response.getState(); console.log('state..!',state); if (state === "SUCCESS") { var cAttachments = response.getReturnValue(); console.log('attachments..!',cAttachments); var rows = []; for(var i = 0;i<cAttachments.length;i++) { var row = {}; row.rowNum = i+1; row.fileId = cAttachments[i].attachmentId; row.fileName = cAttachments[i].attachmentName; row.parentId = cAttachments[i].parentId; row.cDocError = ''; row.showLoadingSpinner = false; rows.push(row); } if(cAttachments.length == 0) rows.push({'rowNum':1,fileId:'','cDocError':'','parentId':'','fileName':'No File Selected..','showLoadingSpinner':false}); component.set("v.rows",rows); } else { alert('Something went wrong.'); } }); $A.enqueueAction(action); } }) view raw MultiFileComp_Helper.js hosted with ❤ by GitHub Styles: This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters .THIS .action-col button{ margin:21%; cursor:pointer; } .THIS .error-msg{ color:#a94442; } .THIS .Name-td input{ border-left: 5px solid #a94442; } view raw MultiFileComp_style.css hosted with ❤ by GitHub Apex cls: This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters public with sharing class AttachmentUploadCon { @AuraEnabled public static list<attachmentWrapper> loadAttachments(Id parentId, string sobjAPIName) { list<attachmentWrapper> awList = new list<attachmentWrapper>(); string qryStr = 'Select Id,Name,(Select Id,Name FROM Attachments) FROM '+sobjAPIName+' where id=:parentId'; list<sobject> records = DataBase.Query(qryStr); for(Sobject sobj : records) { for(Attachment att : sobj.getSObjects('Attachments')) { attachmentWrapper aw = new attachmentWrapper(); aw.parentId = (string)sobj.get('Id'); aw.attachmentId = att.Id; aw.attachmentName = att.Name; awList.add(aw); } } return awList; } public class attachmentWrapper { @AuraEnabled public String parentId; @AuraEnabled public String attachmentId; @AuraEnabled public String attachmentName; } @AuraEnabled public static void deleteAttachment(string attchId) { system.debug('attchId '+attchId); if(string.isNotBlank(attchId)){ list<Attachment> atchList = [select id from Attachment WHERE ID=: attchId]; system.debug('--atchList --'+atchList.size()); if(atchList.size()>0){ delete atchList; } } } @AuraEnabled public static Id saveChunk(Id parnttId, String attachmentName, String attachmentBody, String attachmentType,String attachmentId) { attachmentBody = EncodingUtil.urlDecode(attachmentBody, 'UTF-8'); Attachment oAttachment; if(String.isNotBlank(attachmentId)) { oAttachment = [Select Id,parentId FROM Attachment WHERE Id=:attachmentId]; } else { oAttachment = new Attachment(); oAttachment.parentId = parnttId; } oAttachment.Body = EncodingUtil.base64Decode(attachmentBody); oAttachment.Name = attachmentName; oAttachment.ContentType = attachmentType; upsert oAttachment; return oAttachment.Id; } } view raw AttachmentUploadCon.java hosted with ❤ by GitHub...

Sunday, 5 November 2017

Using external Javascript libraries in Lightning  / Chart JS in Salesforce Lightning

Using external Javascript libraries in Lightning / Chart JS in Salesforce Lightning

To reference a JavaScript library that you’ve uploaded as a static resource, use a <ltng:require> tag in your .cmp or .appmarkup. The afterScriptsLoaded action in the client-side controller is called after the scripts are loaded. Don't use the init event to access scripts loaded by <ltng:require>. These scripts load asynchronously and are most likely not available when the initevent handler is called Lets have a look at the basic initialization of external chart librarbies in Lightning using  Chart JS 1) Import Chart JS min bundle  or get the latest from chart js site ans save it into static resource 2) Create a lighting component bundle and app as shown below sample code. Demo App: This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters <aura:application extends="force:slds"> <c:chartJSCmp /> </aura:application> view raw ChartJSDemo.xml hosted with ❤ by GitHub Component: This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters <aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" controller="ChartJSctrlr"> <ltng:require scripts="{!$Resource.ChartJS270}" afterScriptsLoaded="{!c.afterScriptLoad}"/> <div class="slds-page-header slds-align_absolute-center"> <a href="">ChartJS Demo.</a> </div> <div class="slds-grid"> <!-- Chart 1 grid--> <div class="slds-col slds-p-top_medium slds-size--1-of-1 slds-medium-size_1-of-1 slds-large-size_1-of-2"> <div class="slds-col-header__title slds-align_absolute-center"> <h1 style="font-size: 14pt">Demo Chart#1</h1> </div> <div id = "colors"> <canvas id="colorCanvas" width="400" height="400"></canvas> </div> </div> <!-- Chart 2 grid--> <div class="slds-col slds-p-top_medium slds-size--1-of-1 slds-medium-size_1-of-1 slds-large-size_1-of-2"> <div class="slds-col-header__title slds-align_absolute-center"> <h1 style="font-size: 14pt">Demo Chart#2</h1> </div> <div id = "fruits"> <canvas id="fruitCanvas" width="400" height="400"></canvas> </div> </div> </div> <br></br><br></br> </aura:component> view raw CharJSCmp.xml hosted with ❤ by GitHub ControllerJS: This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters ({ afterScriptLoad : function(component, event, helper) { var action = component.get("c.getChartData"); action.setCallback(this, function(response){ var state = response.getState(); if (state === "SUCCESS") { console.log('--chartData--', response.getReturnValue()); var chartData = response.getReturnValue(); console.log(chartData); if(!$A.util.isEmpty(chartData)){ var chart1_Data = chartData[0]; var canvas1 = document.getElementById("colorCanvas") //**** START OF Chart 1 **** var myChart1 = new Chart(canvas1, { type: 'doughnut', data: { labels: chart1_Data.dataLabels, //["label 1", "Label 2"] datasets: [{ title: 'Chart 1', backgroundColor: ["#bf1114","#ff750c","#ffff47","#037542", "#07127a"], data: chart1_Data.dataValues, //["10", "20"] }] }, options: { maintainAspectRatio: false, title: { display: true, position:"bottom", text: "Chart 1", }, legend: { display: true, position: "top", labels: { fontColor: "#333", fontSize: 12, }, }, } }); //**** END OF Chart 1 **** var chart2_Data = chartData[1]; var canvas2 = document.getElementById("fruitCanvas"); //**** START OF Chart 2 **** var myChart1 = new Chart(canvas2, { type: 'doughnut', data: { labels: chart2_Data.dataLabels, //["label 1", "Label 2"] datasets: [{ title: 'Chart 1', backgroundColor: ["#3cba9f","#8e5ea2","#3e95cd","#e8c3b9", "#f4426e"], data: chart2_Data.dataValues, //["10", "20"] }] }, options: { maintainAspectRatio: false, title: { display: true, position:"bottom", text: "Chart 2", }, legend: { display: true, position: "top", labels: { fontColor: "#333", fontSize: 12, }, }, } }); //**** END OF Chart 2 **** } } }); $A.enqueueAction(action); } }) view raw CharJSCmpController.js hosted with ❤ by GitHub ApexClass: This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters public class ChartJSctrlr { @AuraEnabled Public static list<charWrap> getChartData(){ charWrap cWrap1 = new charWrap(); cWrap1.dataLabels = new list<string>{'Red', 'Orange', 'Yellow', 'Green', 'Blue'}; cWrap1.dataValues = new list<integer>{61, 45, 30, 88, 37}; charWrap cWrap2 = new charWrap(); cWrap2.dataLabels = new list<string>{'Mango', 'Pineapple', 'Apple', 'Banana', 'Grape'}; cWrap2.dataValues = new list<integer>{37, 88, 30, 45, 61}; return new list<charWrap>{cWrap1, cWrap2}; } public class charWrap { @AuraEnabled public list<string> dataLabels; @AuraEnabled public list<integer> dataValues; public charWrap(){ dataLabels = new list<string>(); dataValues = new list<integer>(); } } } view raw ChartJSctrlr.java hosted with ❤ by GitHub...
Pages (3)123 Next
Powered by Blogger.

Visualforce

Apex

Lightening UI

SF Admin