A blog about Salesforce CRM Configuration and development

Saturday, 23 March 2019

Material Designed DataTable In Visualforce Page.

Q. What is material design?

Ans:- Material design is a design technique/language. It uses a grid-based layout, responsive animation, and transition, padding, depth effects show as lightning and shadow. It is designed to optimize user experience with natural motions, 3D effects, and realistic lighting.

DataTable: It is a plug-in for the jQuery Javascript library. It will add features like fast search in the table, paginations, column sorting, etc with the minimum code.



In this example code, I have used DataTable (Jquery plug-in javascript library) in the visualforce page. Find the full code below.

 <apex:page controller="DatatableCntrl" sidebar="false">  
 <head>  
   <apex:includescript value="https://code.jquery.com/jquery-3.3.1.js"/>  
   <apex:includescript value="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"/>  
   <apex:includescript value="https://cdn.datatables.net/1.10.19/js/dataTables.material.min.js"/>  
   <apex:stylesheet value="https://cdnjs.cloudflare.com/ajax/libs/material-design-lite/1.1.0/material.min.css"/>  
   <apex:stylesheet value="https://cdn.datatables.net/1.10.19/css/dataTables.material.min.css"/>  
   <script>  
   j$ = jQuery.noConflict();  
   j$(document).ready( function () {  
     var accTable = j$('[id$="accTable"]').DataTable({  //datatable 
        columnDefs: [  
     {  
       targets: [ 0, 1, 2 ],  
       className: 'mdl-data-table__cell--non-numeric'  
     }  
   ]  
     });  
   });  
   </script>  
   <style>  
     div.dataTables_wrapper div.dataTables_filter {  
     text-align: right;  
     margin-right: 2%;  
     /* border-radius: 2px; */  
     /* height: 51px; */  
   }  
   </style>  
 </head>  
 <body>  
   <table id="accTable" class="mdl-data-table" style="width:100%">  
     <thead>  
       <tr>  
         <th>Name</th>  
         <th>Billing State</th>  
         <th>Website</th>  
       </tr>  
     </thead>  
     <tbody>  
       <apex:repeat value="{!accList}" var="acc">  
         <tr>  
           <td>{!acc.Name}</td>  
           <td>{!acc.BillingState}</td>  
           <td>{!acc.Website }</td>  
         </tr>  
       </apex:repeat>  
     </tbody>  
   </table>  
 </body>  
 </apex:page>  

 public class DatatableCntrl{  
   public List<Account> accList {get; set;}  
   public DatatableCntrl(){  
     accList = [SELECT Name, BillingState,Website FROM Account where BillingState!='' and Website !='' order by name ];  
   }  
 }  


References:

Share:

Make only one record active at a time of same record type.


Scenario: Make only one contact record active at a time of the same record type on Account.

Solution: Using Apex Trigger: Create a trigger on the contact object for insert and update event. Find the code below.

 /* Name: deactivateContact  
  * Description: Make only one record active at a time of same record type.  
  * Created By: 23/03/2019  
  * Last ModifiedDate: 23/03/2019  
  * Created By: Arun Kumar  
 */  
 trigger deactivateContact on Contact (before update, before insert) {  
   if(Trigger.isBefore){  
     if(Trigger.isUpdate || Trigger.isInsert){  
        if(deactivateContactHelper.isFirstTime){ // check for recursive call  
         deactivateContactHelper.isFirstTime = false;  
         deactivateContactHelper.updateContact(Trigger.new);   
        }  
     }  
   }  
 }  

 /* Name:deactivateContactHelper  
  * Description: Update isActive field on contact( Only one contact record will be active at a time of same record type).  
  * Created Date: 23/03/2019  
  * Last ModifiedDate: 23/03/2019  
  * Created By: Arun Kumar  
 */  
 public class deactivateContactHelper {  
   public static boolean isFirstTime= true; // for recursive call check  
   // update isActive field ( Only one contact record will be active at a time of same record type).  
   public static void updateContact(List<Contact> contactList){   
     set<id> parentId = new set<id>();  
     set<id> recordId = new set<id>();  
     set<id> recordTypeIdSet = new set<Id>();  
     for(Contact c: contactList){  
       if(c.isActive__c){  
         parentId.add(c.AccountId); // accountid  
         recordId.add(c.id); // record id  
         recordTypeIdSet.add(c.recordTypeId); // recordtype id  
       }  
     }  
     List<contact> ContactForUpdate = new List<contact>(); // contact list for update  
     for(Contact con:[select id,isActive__c from contact where accountid IN: parentId and Id NOT IN: recordId and recordTypeId IN:recordTypeIdSet]){  
       con.isActive__c = false;// isActive__c = FALSE  
       ContactForUpdate.add(con);   
     }  
     if(ContactForUpdate.size()>0){  
       try{  
         update ContactForUpdate;// Update rest contact list  
       }  
       catch(Exception e){  
         system.debug('Exception has occred! ' +e.getMessage());  
       }  
     }   
   }  
 }  
Share:

Friday, 22 March 2019

Count number of Active contact on Account


Count # Number of active contact on Account record.

Scenario: Calculate #NoOfActiveContact for Account record.

Solution: Create an Apex Trigger on Contact object and calculate for all case (insert, update, delete, undelete) 

 trigger CountActiveContact on Contact (after insert,after update,after delete,after undelete) {  
   Set<id> parentId = new Set<Id>(); // AccountId Set  
   if(Trigger.isAfter){  
     if(Trigger.isUpdate || Trigger.isInsert || Trigger.isUndelete){  
       for(Contact con: Trigger.new){  // return list of new sObject record
         if(con.accountId !=null){  //check if accountid is not null
           parentId.add(con.accountId);  //add accountid in set
           if(Trigger.isUpdate){ // check for update   
             if(Trigger.oldMap.get(con.id).AccountId != con.AccountId){ // check old accountid with new  
               parentId.add(Trigger.oldMap.get(con.id).AccountId);//accountid set  
             }  
           }  
         }  
       }  
     }  
     if(Trigger.isDelete){// delete  
       for(Contact con: Trigger.old){  // return list of deleted sObject record
         parentId.add(con.accountId);  
       }  
     }  
     List<Account> accListForUpdate = new List<Account>();  //account list for update
     for(Account acc: [select id,ARI__No_Of_Contact__c,(select id from contacts where isActive__c=true) from Account where id IN: parentId]){  
       acc.ARI__No_Of_Contact__c = acc.contacts.size(); // get size of contact list on account 
       accListForUpdate.add(acc);  //add acc object in list
     }  
     if(accListForUpdate.size()>0){  //check for list size
       try{  
         update accListForUpdate;  // update account list
       }  
       catch(Exception e){  
         system.debug('Exception has occured! '+e.getMessage());  
       }  
     }  
   }  
 }  

Share:

Wednesday, 20 March 2019

Sort wrapper class list in Apex

Sort wrapper list based on selected records.


Visualforce page:
 <apex:page showHeader="false" controller="WrapperListSortCntrl" >  
 <html>  
   <head>  
     <apex:slds />  
   </head>  
   <body>  
     <apex:form >  
       <div class="slds-page-header">  
          My Product  
       </div>  
       <table class="slds-table slds-table--bordered">  
         <thead>  
           <tr>  
             <th> Select</th>  
             <th> Name </th>  
             <th> Product Family </th>  
             <th> Description</th>  
             <th> Active</th>  
           </tr>  
         </thead>  
         <tbody>  
           <apex:repeat value="{!ProductList}" var="p">  
             <tr>  
               <td><apex:inputcheckbox value="{!p.selectcheck }" styleClass="slds-checkbox"/></td>  
               <td>{!p.prd.Name}</td>  
               <td>{!p.prd.Family}</td>  
               <td>{!p.prd.Description}</td>  
               <td>{!p.prd.IsActive}</td>  
             </tr>  
           </apex:repeat>  
         </tbody>  
       </table>  
     </apex:form>   
   </body>  
 </html>    
 </apex:page>  
Apex Class:
 /* Name: WrapperListSortCntrl  
   Description: Wrapper List Sort  
   Created Date: 20/03/2019  
   LastModified Date: 20/03/2019  
   Created By: Arun Kumar  
 */  
 public class WrapperListSortCntrl{  
   public List<WrapperCls> ProductList{get;set;}  
   public WrapperListSortCntrl(){  
     ProductList = new List<WrapperCls>();  
     system.debug('Insider');  
     fetchProducts();  
   }  
   public void fetchProducts(){  
     for(Product2 p:[select id,Name,Family,Description,IsActive from Product2]){  
       Boolean check = false;  
       if(p.isActive){  
         check = true;  
       }  
       ProductList.add( new WrapperCls(check, p));   
     }  
     system.debug('ProductList: '+ProductList);  
     ProductList.sort(); // this Wrapper list will be sort according to checkbox selected (isActive =true)  
   }  
   //Wrapper cls implements Comparable Interface  
   public class WrapperCls implements Comparable { //Adds sorting support for Lists that contain non-primitive types, that is, Lists of user-defined types.  
     public Boolean selectcheck {get;set;}    
     public Product2 prd{get;set;}    
     public WrapperCls(Boolean selectcheck, Product2 prd){  
       this.selectcheck = selectcheck ;  
       this.prd = prd;  
     }  
     public Integer compareTo(Object ObjectToCompare) { //Returns an Integer value that is the result of the comparison.  
       WrapperCls compareToWrapperCls = (WrapperCls)ObjectToCompare;  
       if (compareToWrapperCls.selectcheck )   
         return 1;  
       else  
         return 0;  
       }  
     }  
 }  

Reference:

Comparable Interface:https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_comparable.htm
Share:

Sunday, 17 March 2019

Show the uploaded image on the detail page.





Hello,

I have recently worked on the interesting/good requirement and just want to share this with you:

Requirement: There should be a detail page button on object record and the user can upload the image file to that record. The uploaded image file should show on the record details page.

Solution: Created a visualforce page through which the user can upload the image in the content file system in Salesforce. Now the main thing is to show the uploaded image file on the record detail page. For that, I had created a rich text field and inserted file downloadable URL in the <image> tag.

Q. Where we can find the 'ContentDownloadUrl ' after file upload? 

Ans- The ContentDistribution object: (Represents information about sharing a document externally). We need to insert the ContentDistribution object record after ContentVersion insertionAfter CD (ContentDistribution) record insertion, you will get the 'ContentDownloadUrl' for that file. Find more information on ContentDistribution in Salesforce doc here.

Create a detail page button on the Account object like the screenshot below:














Visulforce page:
 <!-- Name: UploadImages  
    Decription: Upload images in files object and show them on richtex field on record.  
    Created Date: 17/03/2019  
    LastModified Date: 17/03/2019  
    Created By: Arun Kumar  
 -->  
 <apex:page controller="uploadImageCntrl" sidebar="false">  
  <html>  
    <head>  
      <apex:slds />  
      <style>  
        .slds-scope .slds-page-header {  
         padding: 1rem 1rem;  
         /* border-bottom: 1px solid rgb(221, 219, 218); */  
         /* border-radius: .25rem; */  
         background: rgb(243, 242, 242);  
         background-clip: padding-box;  
         /* box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.10); */  
         border: 1px solid rgb(221, 219, 218);  
       }  
       #bodyPart{  
         border: 1px solid rgb(221, 219, 218);  
         padding:1rem 1rem;  
       }  
      </style>  
    </head>  
    <body>  
      <apex:form >  
      <div class="slds">  
        <div class="slds-grid">  
          <div class="slds-col slds-size--12-of-12">  
            <div class="slds-page-header">  
              Upload Image  
            </div>  
          </div>  
        </div>  
        <div id="bodyPart">  
          <apex:inputFile value="{!imageFile}" styleClass="" />  
          <apex:actionRegion >  
             <apex:commandButton value="Upload" action="{!uploadImg}" Styleclass="slds-button slds-button--brand" />  
          </apex:actionRegion>  
        </div>  
      </div>  
      </apex:form>  
    </body>  
  </html>  
 </apex:page>  
Apex controller
 /* Name: uploadImageCntrl   
   Description: Upload files and show image in richtext field on object record page.  
   Created Date: 17/03/2019  
   LastModified Date: 17/03/2019  
   Created By: Arun Kumar  
 */  
 public with sharing class uploadImageCntrl {  
   public transient Blob imageFile{get;set;}  
   public string parentRecId ='';  
   public void uploadImageCntrl(){  
   }  
    public PageReference uploadImg() {  
     parentRecId = ApexPages.currentPage().getParameters().get('id');  
     system.debug('record id: ' +parentRecId );  
     //ContentVersion  
     ContentVersion conVer = new ContentVersion();  
     conVer.ContentLocation = 'S'; // S specify this document is in SF, use E for external files  
     conVer.Title = 'Test File';   
     conVer.PathOnClient = 'Test File';  
     conVer.VersionData = imageFile; //   
     insert conVer;  
     ContentVersion cv = [select id,ContentDocumentId from ContentVersion where id =: conVer.id];  
     //Create ContentDocumentLink  
     ContentDocumentLink cDe = new ContentDocumentLink();  
     cDe.ContentDocumentId = cv.contentDocumentId;  
     cDe.LinkedEntityId = parentRecId; // you can use objectId,GroupId etc  
     cDe.ShareType = 'V'; // Inferred permission, checkout description of ContentDocumentLink object for more details  
     //Insert content document link  
     insert cDe ;  
     //ContentDistribution: Represents information about sharing a document externally  
     ContentDistribution cd = new ContentDistribution();  
     cd.Name = 'Test File';  
     cd.ContentVersionId = conVer.Id;  
     //insert   
     insert cd;  
     ContentDistribution distribution = [select Name,ContentDownloadUrl from ContentDistribution where id=: cd.id];  
     Account acc = [select id,ARI__Images__c from Account where id=: parentRecId]; //ARI__Images__c (ARI__ is Namspace. it will be different in your case)   
     if(acc.ARI__Images__c == null){  
       acc.ARI__Images__c ='';  
     }  
     acc.ARI__Images__c += '<img src="'+distribution.ContentDownloadUrl+'" width="478" height="247">'+'</img><br/>';   
     update acc;  
     return null;  
   }  
 }  
Output:










Reference: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_contentdistribution.htm

Hope this blog post helps many.

Happy Coding... :)
Share:
Trailhead Profile


Follow by Email

Total Pageviews

Followers

Popular Posts

Powered by Blogger.

Contact form

Name

Email *

Message *