Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

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.

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.

Simple Loader image for Visualforce Page.

Hello guys,

I am gonna show you simple way to pop up loader image i.e status image for loading purpose using CSS and javascript function.

Using simple html div and Javascript you can create your status loader.

Below i am gonna show you simple html tag for it. you can call javascript function on onclick method to show loader and hide it on oncomplete.

ADD BELOW STYLE TO YOUR VF PAGE

#filter{ 
      display:none;
      background-image: url({!URLFOR($Resource.Static_Resource_Main,'Static_Resource_Main/loading32.gif')});
      z-index:10000;
      position:fixed;
      top:0%;left:0%;
      width:100%;
      height:100%;
      background-repeat:no-repeat;
      background-position:center;
      background-color: #ffffff;
      opacity:0.6;
      filter:alpha(opacity=50);
} 
Call startProces method when you call action( Controller function or any function after which you want to show loading image).

 

function startProcess()
{
      $('#filter').show();
}

function endProcess ()
{
      $('#filter').hide();
}   
Add below Div tag at the start of body tag or form.

<center>
    <div id="filter"></div>
</center>                        
startProcess will add display: block css to div.
endProcess  will hide the div.

Its just awsomeness of css.

Hope you will like it.
Enjoy coding....

Custom button: How to pass currency field to an Apex web service?


you can try using the VALUE function to get the decimal value from the currency field before passing it to the webservice method.
Example:
We want to pass decimal value of Opportunity Amount. Then we use below code in custom button to pass decimal value to web-service.
{!REQUIRESCRIPT("/soap/ajax/10.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")}

var amt = {!VALUE(TEXT(Opportunity.Amount))};
var retVal = sforce.apex.execute("WSclassname", "WSmethod", {oppAmt:amt});
alert (retVal) ;
window.location.reload() ;

Custom Picklist lookup using javascript in Visual page

In this post I'm gonna show you how to create simple custom picklist lookup in Visual page using javascript.

We will use window eventlistner to get data from child window open by parent window.

Here is snippet of my simple vf page.

  
<apex:page >
    <script>
        function open_pop_up(idx, field, sObj){
            var child = window.open('/apex/picklistLookup?idx='+idx+'&field='+field+
'&sObj='+sObj+'', '_blank', 
'toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400')
            console.log('==> Child: ' + child);
        }
        
        var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
        var eventer = window[eventMethod];
        var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
    
        //Listen to message from child window
        eventer(messageEvent,function(e) {
            console.log('parent received message!: ',e.data);
            var dataArr = e.data.split(':'); 
            var elmtId = e.data.substring(0, e.data.lastIndexOf(':'));
            var datavalue = e.data.substring(e.data.lastIndexOf(':') + 1,e.data.length);
            document.getElementById(elmtId).value = datavalue;
        },false);  
        
    </script>
    
    <input id="testId" value="" onclick="open_pop_up('testId','CustomerPriority__c',
'Account');"/>
</apex:page>

Let me explain the code.

when we click on input it will open popup lookup window.
Here i have use my custom picklist field CustomerPriority__c of Account Object for test data.

Now new vf page for lookup popup window.

  
<apex:page controller="PicklistLookupCon" showHeader="false">

    <apex:variable value="{!0}" var="rowNum"/>
    
    <table>
        <tr>  
            <td></td>  
            <td>
                <input type="button" value="Insert Selected" onclick="InsertSelected()" class="btn"/>
            </td>
        </tr>
        <apex:repeat value="{!picklistValues}" var="plv">
            <tr>
                <td>
                    <input type="checkbox" onclick="selectValue('{!rowNum}', this.checked, '{!plv}')"/>
                </td>
                <td>{!plv}</td>
            </tr>
            <apex:variable value="{!rowNum+1}" var="rowNum"/>             
        </apex:repeat>            
    </table>
    
    <script type="text/javascript">
        var arrValue  = new Array();
               
        function selectValue(id, isChecked, value){

            if(isChecked == true){
                arrValue[arrValue.length] = value;
            }else{
                var index = arrValue.indexOf(value);
                arrValue.splice(index,1);
           }  
        }
           
        function InsertSelected(){
            console.log(window.parent.opener);
            var win = window.parent.opener;
            var dataStr= '';
            
            for(var k=0;k<arrValue.length;k++){
                if(k==0) dataStr = arrValue[k];
                else dataStr +=','+arrValue[k];
            }
            win.postMessage('{!$CurrentPage.parameters.idx}:'+dataStr, window.parent.opener.location.href); 
            window.parent.close();
        }
  </script> 
</apex:page>

controller:

public without sharing class PicklistLookupCon {

    string sObj = Apexpages.currentpage().getParameters().get('sObj');
    string field = Apexpages.currentpage().getParameters().get('field');

    public picklistLookupCon(){
    
    }
        
    public List picklistValues{
      get{
          if(picklistValues!=null)
              return picklistValues;
          else{
              picklistValues = new List();
              
              Map gd = Schema.getGlobalDescribe(); 
              Schema.SObjectType ctype = gd.get(sObj);
              Map fmap = ctype.getDescribe().fields.getMap();
              Schema.DescribeFieldResult fieldResult = fmap.get(field).getDescribe();
              List ple = fieldResult.getPicklistValues();   
              
              for( Schema.PicklistEntry f : ple){
                  picklistValues.add(f.getValue());
             }
          }
          return picklistValues;
      }
      set;
    }
    
 }

That's it.

Yepppieee you done it.