Access component variable in Callback function Salesforce Lightning component

You might have face issue somewhere in component where you are triggering some JavaScript callback function, and in callback function you want to perform some logic on component variable but you got stuck in accessing component.

Becuase modifiing component outside the normal rerending lifecycle is not allowed. 

for example you using setTimeout().

To resolve this issue wrap your callback function into $A.getCallback(), which modifies a component outside the normal rerendering lifecycle.


window.setTimeout(
    $A.getCallback(function() {
        component.set("v.attribute", "attributevalue");
    })
);

 

Hope this will help! Enjoy Coding!!!

For more information visit here.

Application and Component in Salesforce lightning

 This blog will be focusing on two event types provide by Salesforce. One is Application Events and another is component Events and how we can pass values from one component to another.

Application Events

When you want to pass values between two independent component at that time we will use Application Events. Lets say you have two independent, say SENDER component which takes Name as input from the user and passes its value to say RECEIVER component.

Steps to create Application Event:

1. Create a Event with type as APPLICATION 

<aura:event type="APPLICATION" description="Description for Event">
          <aura:attribute name="param" type="Object" description="Description for parameter"/>
      </aura:event>

2. Register event in SENDER component

<aura:registerEvent name="senderEvent" type="c:EventName">
<aura:attribute type="String" name="firstname" />
<lightning:input type="text" name="firstname" value="{!v.firstname}" />
<button onclick="{!c.callEvent">Send</button>

JS controller 
({
     callEvent : function(cmp, event, helper) {
        var e = $A.get("e.c:EventName");  // get Event 
        e.setParams({ "param" : cmp.get("v.firstname")}; //set param value for event
        e,fire();  // fire event

    }
})

3. Now Handle event in RECEIVER component by adding handler for event
<aura:handler event="c:EventName" action="{!c.receiveParam}" /> //hadler to handler event
JS controller
({
    receiveParam : function(cmp, event, helper) {
        var param = event.getParam("param"); //get param value 
        console.log("Value recieved from SENDER component is: " + param);
    }
})

Every component which has Handler can receive param value send by SENDER component for APPLICATION type event.

Component Event

Lets say you want pass value between child to parent in this case you can use component event. Here sender will be child component and reciever will be parent component.

Steps for it.

1. Create event of type COMPONENT

<aura:event type="COMPONENT" description="Description for Event">
          <aura:attribute name="param" type="Object" description="Description for parameter"/>
      </aura:event>

2. Register event in SENDER component same as in Step 2 of Application Event
    attribute name for aura:registerEvent should be same in aura:handler name attribute.

here: name="senderEvent"

<aura:registerEvent name="senderEvent" type="c:EventName"> 
<aura:attribute type="String" name="firstname" />  
<lightning:input type="text" name="firstname" value="{!v.firstname}" /> 
<button onclick="{!c.callEvent">Send</button>

JS controller 
({
     callEvent : function(cmp, event, helper) {
        var e = $A.get("e.c:EventName");  // get Event 
        e.setParams({ "param" : cmp.get("v.firstname")}; //set param value for event
        e,fire();  // fire event

    }
})

 

3. Add handler with name="senderEvent" 

<aura:handler name="senderEvent" event="c:EventName" action="{!c.receiveParam}" />
//handler to handle event

 

It's mandatory in Component event to set name attribute in event registration and handler, as param can be exchange in parent child component only.


Hope you like the post! Enjoy Coding.

Page border on cover page visualforce as word document

Hello folks,

In this blog I am going to give example to how to apply border on cover page of visualforce page word document.

To load visualforce page as word document you need to add attribute ContentType="application/msword#name_of_Document.doc". you can replace name_of_document with file name you want to add.

lets jump on code snippet to add page border.Below style sheet will add page border on cover page.



          @page Section1 {
                size: 8.5in 11in;
                margin: 0in 1in 0.5in 1in;
                mso-header-margin: 0.5in;
                mso-header: h1;
                mso-footer: f1;
                mso-footer-margin: 0.5in;
                mso-paper-source: 0;
                mso-page-border-display: first-page;
                font-family: Calibri; 
                mso-border-alt: solid black 2pt;
                mso-page-border-offset-from: edge;
                padding: 20px 20px;
         }



      mso-border-alt: solid black 2pt;
      mso-page-border-offset-from: edge;


Above line will add border to page and adding padding to section will add padding to page border.

Hope this will help, Please comment your question or suggestions.




Drag and drop sorting in visualforce page using angularJs


Hello folks,

In this blog I am going to give example to apply drag-drop sorting in visualforce page with use of angularJs.

Lets start with creatting basic Html template to host our app. We will use the ng-app and ng-controller directives to link up the body tag to our Angular application. At the bottom we will include our required libraries.


Prerequisite:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-sortable/0.15.0/sortable.min.js"></script>


In this code we define an Angular module and name it ngApp, and include the ui.sortable in the requires parameter. This ui.sortable is what wires up angular-ui-sortable to our module. We also define the controller called myController for our module and inject the Angular $scope object. This is where we will set up our Angular sortable.


<script >
      var ngApp = angular.module('myNgApp', ['ui.sortable']);
      ngApp.controller('myController', function ($scope) {

           $scope.names = [ "Test1", "Test2", "Test3" ];

      });


</script>
Now lets use this $scope name variable to display data in Ul by adding ng-model Directive on it and ng-repeat to loop over array.  To make this list sortable, all we need to do is use the ui-sortable directive.
<ul ui-sortable="sortableOptions" ng-model="names">
      <li ng-repeat="person in people" class="list-group-item">{{name}}</li>
</ul>
To see this in action let’s add a pre element and bind it to the people array that will show the order of array in real time.
<pre>{{names}}</pre>

Final code will look like below.
<apex:page standardStylesheets="false" sidebar="false" showHeader="false">
    <apex:slds />
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js">
     </script>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/
jquery-ui.min.js"></script>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/
angular.min.js"></script>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-sortable/
0.15.0/sortable.min.js"></script>
    <script>
          var ngApp = angular.module('ngApp', ['ui.sortable']);
          ngApp.controller('myController', function ($scope) {
    
               $scope.names = [ "Test1", "Test2", "Test3" ];
    
          });
    </script>
    <body ng-app="ngApp" ng-controller="myController">
        <article class="slds-card">
            <div class="slds-card__header slds-grid">
                <div class="slds-media__body">
                    <h2 class="slds-card__header-title">
                      <a href="javascript:void(0);" 
class="slds-card__header-link slds-truncate" title="Names">
                        <span>Name List</span>
                      </a>
                    </h2>
                </div>
                
            </div>
            <div class="slds-card__body slds-card__body_inner">
                <ul ui-sortable="sortableOptions" ng-model="names" 
class="slds-has-dividers_top-space">
                    <li ng-repeat="name in names " class="slds-item">{{name}}</li>
                </ul>
                <pre>{{names}}</pre>
            </div>
        </article>
    </body>
    
</apex:page>

Output:




Hope it will help. Let me know your comments.

Go to specific Page number in DataTable Jquery


You want to go to specific page number using Jquery in DataTable Pagination then you can use below to apply.

1. Go to specific page number

    $(document.getElementById('idofTable').DataTable().table.fnPageChange( pagenumber );

2. Destroy DataTable
 
     var table = $(document.getElementById('idofTable').DataTable();
     table.fnDestroy();


That's all in this post.
Hope this helps..

Happy Coding..!!!!!!

Create CSV file using Jquery/ JavaScript


Below is sample Html and Jquery to create CSV using Jquery or Javascript.

if have issue in generating data containing comma (,) use below code.


<table id="tableId">

    <thead>

        <tr><th>Heading</th><th>Heading</th></tr>

    </thead>

    <tbody>

        <tr><td>cell</td><td>cell2</td></tr>

    </tbody>

</table>

<input type="button" value="select table" onclick="
createCSVFile(document.getElementById('tableId') );">
<script> function createCSVFile(tablehtml) { export_table_to_csv(tablehtml,'report.csv'); } function download_csv(csv, filename) { var csvFile; var downloadLink; // CSV FILE csvFile = new Blob([csv], {type: "text/csv"}); // Download link downloadLink = document.createElement("a"); // File name downloadLink.download = filename; // We have to create a link to the file downloadLink.href = window.URL.createObjectURL(csvFile); // Make sure that the link is not displayed downloadLink.style.display = "none"; // Add the link to your DOM document.body.appendChild(downloadLink); // Lanzamos downloadLink.click(); } function export_table_to_csv(html, filename) { var csv = []; var doc = document.implementation.createHTMLDocument("New Document"); var p = doc.createElement("p"); p.innerHTML = html; doc.body.appendChild(p); var rows = doc.querySelectorAll("table tr"); for (var i = 0; i < rows.length; i++) { var row = [], cols = rows[i].querySelectorAll("td, th"); for (var j = 0; j < cols.length; j++) { //check if data contains comma if(cols[j].innerText.trim().includes(',')){ row.push('"'+cols[j].innerText.trim() +'"'); } else{ row.push(cols[j].innerText.trim()); } } csv.push(row.join(",")); } // Download CSV download_csv(csv.join("\n"), filename); } </script>
Thanks for visiting.

If have any doubt or suggestions please comment.

Have happy coding. :) !!!!!!!

Copy to Clipboard using JavaScript.

Below is the easiest way to use JavaScript to copy element to Clipboard.



<table id="tableId">

    <thead>

        <tr><th>Heading</th><th>Heading</th></tr>

    </thead>

    <tbody>

        <tr><td>cell</td><td>cell2</td></tr>

    </tbody>

</table>



<input type="button" value="select table"

   onclick="copyElementContents( document.getElementById('tableId') );">


<script>

    function copyElementContents() {

            var el = $('*[id*=pbt]')[0]; // element to be copied to clipborad

            var body = document.body, range, sel;

            if (document.createRange && window.getSelection) {

                range = document.createRange();

                sel = window.getSelection();

                sel.removeAllRanges();

                try {

                    range.selectNodeContents(el);

                    sel.addRange(range);

                } catch (e) {

                    range.selectNode(el);

                    sel.addRange(range);

                }

                document.execCommand("copy");

                sel.removeAllRanges();

            } else if (body.createTextRange) {

                range = body.createTextRange();

                range.moveToElementText(el);

                range.select();

                range.execCommand("copy");

               

            }

        }

</script>
Enjoy Coding .

If have any doubt please comment.

Thanks.