Posts By Chirag Mehta

How to define filename for a Visualforce generated PDF (renderAsPdf) ?

When rendering a visualforce page as a PDF, the filename of the PDF (by default) is the name of the page which may be annoying at times. Annoying as every time the file is generated, it will be generated with same name and will lead to cause confusion with the user. If opened multiple times, files will be saved as invoice.pdf, invoice[1].pdf, invoice[2].pdf … and so on. Ideally you should be able to define the name of the generated PDF but that’s not something well documented anywhere.

To rescue (as always) comes Salesforce blogs/forums [1][2].

In order to set filename for generated PDF you need to set the Content-Disposition header. In constructor of the Visualforce controller use below code:

Apexpages.currentPage().getHeaders().put('content-disposition', 'attachment; filename=AccountReport.pdf'); //In case you want to download pdf

or
Apexpages.currentPage().getHeaders().put('content-disposition', 'inline; filename=AccountReport.pdf'); //In case you want to open pdf in browser

Please Note : If you want to make the file name dynamic you will need to refer to several RFCs on how to correctly encode the filename. E.g. if it contains spaces it will need to be quoted. If there are non-ASCII characters or it is longer than 78 characters it needs to be Hex encoded (RFC 2184).

References
[1] https://salesforce.stackexchange.com/questions/4118/how-can-i-specify-a-file-name-for-a-visualforce-generated-pdf
[2] https://developer.salesforce.com/forums/ForumsMain?id=906F000000095BPIAY

Visualforce Jquery Select List with Search feature

Lets say you have a requirement where-in you are displaying a select-list (picklist) on a visualforce page for user selection. Based on user selection you are doing some operation. Now if this select list is too big (i.e., is list of  50+ items), then its really hard to select a particular item as visualforce select list doesn’t support searching of options inside a select list.

Inorder to provide similar functionality, I google’d and found a really nice jquery plugin – Chosen. Convert long, unwieldy select boxes much more user-friendly.

Below is simple to follow steps to incorporate same in a visualforce page.

Step1 : Import necessary Jquery+Chosen JS & CSS into Static Resource. Download @ https://github.com/harvesthq/chosen/releases

Step2 : Include above imported js and css in visualforce page

<!– Include Chosen JQuery Plugin Javascript and CSS Files –>
<apex:includeScript value=”{!URLFOR($Resource.chosen_jquery_plugin, ‘chosen.jquery.js’)}”/>
<apex:includeScript value=”{!URLFOR($Resource.chosen_jquery_plugin, ‘chosen.jquery.min.js’)}”/>
<apex:includeScript value=”{!URLFOR($Resource.chosen_jquery_plugin, ‘docsupport/prism.js’)}”/>
<apex:stylesheet value=”{!URLFOR($Resource.chosen_jquery_plugin, ‘docsupport/prism.css’)}”/>
<apex:stylesheet value=”{!URLFOR($Resource.chosen_jquery_plugin, ‘chosen.css’)}”/>

Step3: Include script to convert select into select with search

<script>
j$ = jQuery.noConflict();
j$(document).ready(function() {
j$(“select[id*='IdOfSelectElement']“).chosen();
});
<script>

Salesforce – Generating Stub Code(Jar) from a WSDL

When integrating any non native application (JAVA or NET or ..) with salesforce, you need to have the salesforce API library in place that can be referred/used as a referenced library in project being developed. This library is the the one that acts as face to salesforce i.e., intermediary between your application and salesforce.

Simple yet important step of such type of integration is to generate stub code (jar file) from wsdl (salesforce enterprise or partner wsdl) and though such a simple step, we (at least I) always forget (or I should say cant recall easily) the step on how to generate same.

Below are three easy steps to generate stub code (jar) from a wsdl:

  1. Download Enterprise (Partner) WSDL by navigating to Setup -> API – > Enterprise (Partner) WSDL (right click and save file as “abc.wsdl”, ensure extension “.wsdl” is there).
  2. Download Force.com Web Service Connector (WSC) [1]. The Force.com Web Service Connector (WSC) is a high performing web service client stack implemented using a streaming parser. WSC also makes it much easier to use the Force.com API (Web Services/SOAP or Asynchronous/REST API). You can download a pre-built WSC jar file from: http://code.google.com/p/sfdc-wsc/downloads/list
    Now generate Stub Code from a WSDL. Run wsdlc on the WSDL you have downloaded:

    java -classpath wsc-xx.jar com.sforce.ws.tools.wsdlc *wsdl* *jar.file*
    or
    java -jar wsc-23.jar *wsdl* *jar.file*

    wsdl is the name of the WSDL file
    jar.file is the name of the output jar file that wsdlc generates
    You can include an optional argument: -Dpackage-prefix=myprefix

  3. Now write your client application. Add wsc-xx-min.jar and jar.file (generated by wsdlc) to your classpath, then compile and run your client application.

With this you are all set with stub code / library and ready to make soap API calls to Salesforce.

Enjoy Coding!

References:
[1] https://code.google.com/p/sfdc-wsc/

Javascript (jQuery) code to fetch Salesforce Lead Convert Custom Field Mappings (in terms of API Names)

Yesterday came across a requirement to list down Lead Convert Custom Field Mappings in terms of API Names ie Lead Field1__c maps to Account/Contact/Opportunity Field1__c. Salesforce UI doesn’t give that option to extract same. Neither any metadata API got that, really strange that there’s no way I can extract Lead Convert Custom Field Mappings (in terms of API Names). Is there any? please help in case I’m missing some standard way of extracting that out?

Easiest option could have been that I sit down and do manual and tedious way of reading each field label finding its API Name and record the same in excel, but this doesn’t seem viable option for an org with 100+ lead convert field mappings. As I couldn’t find one using all standard approaches, I started thinking of wicked ways of achieving it. And as usual Javascript (jQuery) comes to rescue party!

Login to Salesforce Org in Chrome or FF Browser,
Navigate to lead convert field mappings page (Select Your Name | Setup | Customize | Leads | Fields | Map Lead Fields),
Open Javascript Console,
Now load jQuery first (you can do same by loading any existing jQuery booklet or userscript too) by executing below code in JS Console.


var jq = document.createElement('script');
jq.src = "//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
$j=jQuery.noConflict();

Now comes the main code which will output LeadFieldAPIName, Account/Contact/Opportunity Field APIName, Account or Contact or Opportunity. Execute below code too in JS Console.

//Traverse across all Select elements
$j("select").each(function () {

//Consider only the ones with a mapping selected
if (this.value != '') {

//Fetch Object Name to which this particular Lead field is mapped, whether its Account or Contact or Opportunity
var objectname = $(this).find('option:selected').text().split(".")[0];

//Tricky Part : As this lead convert field mappings page doesn’t store Lead field API Names, it only contains lead field ID (15 digit SFDC ID) so we will have to do AJAX request of LEAD field detail webpage to fetch LEAD API Name corresponding to lead field ID
var contentText = $.ajax({url: "/" + this.name,async: false}).responseText;

//In fetched content, search and extract field API Name
var fromfield = $(contentText).find('td').filter(function () {
return $(this).text().indexOf('API Name') === 0;
}).closest('td').next().html();

//Similarly AJAX request for Account/Contact/Opportunity field detail page to fetch respective field API Name
contentText = $.ajax({url: "/" + this.value,async: false}).responseText;

//In fetched content, search and extract field API Name
var tofield = $(contentText).find('td').filter(function () {
return $(this).text().indexOf('API Name') === 0;
}).closest('td').next().html();

//Output LeadAPIName, Account/Contact/Opportunity APIName, Account or Contact or Opportunity
console.log(fromfield + ',' + tofield + ',' + objectname);

}});

Please Note:

  • This isn’t most neat and recommended way, so if you come across something really clean and less network consuming solution please share your solutions in comments below
  • I’m not an expert in jQuery, so there might be obvious and recommended ways of coding jQuery and my above coding might sound nascent way of handling jQuery, so please ignore my lack of knowledge around jQuery and help me to optimize same.
  • Fetching Lead/Account/.. Field API Name from Field ID might be done using other ways too (describe API Calls?), but thought of doing it in just one script, so did that using AJAX calls and parsing retrieved webpage content
  • As always, feedback/suggestions are always welcome

Auto-Refresh Salesforce Dashboard every 5, 10 or 15 … seconds, minutes or hours …

Is there a way we can have Salesforce Dashboard Auto-Refresh every few seconds (not recommended) or every x minutes or every x hours …?

Standard Out of box functionality does allow to refresh dashboard, but the lowest level of refresh interval is DAILY or WEEKLY or MONTHLY.

Lets say you want to have(display) a Sales Monitor always LIVE showing real time data, how do you achieve that?

There’s no direct way of doing it, but JS (as always) comes to the rescue …

  1. Log in to Computer (which is streaming output to LIVE monitor) , open Chrome browser (will try to update the script later to make it work in all browsers)
  2. Login to Salesforce and Navigate to desired Dashboard
  3. Delete url from  address/url bar, type (or copy+paste) below code and hit enter in address/url bar. (Make sure javascript: at start is there, chrome does remove it when copy pasted)

    javascript:function autorefresh() {document.getElementById('refreshButton').click();setTimeout(autorefresh, 5000);}autorefresh();

  4. Now do a full screen and enjoy Dashboard Live Monitor :)

 Please Note:

  1. 5000 represents 5000 milli seconds ie 5 seconds, so change the same according to your requirements ie if you want it to refresh every minute change the value to 60000
  2. This is not a recommended way, as its a tweak and might not work in future. (But as of now its working great and helps in having real time monitor of your favorite dashboard, so enjoy!)

Might be this can be an admin tool or a chrome extension, will try to make one when I get time and chance :)

I’ll carry you out every morning until death do us apart …

Today I came across a really nice story, which touched my heart. This probably is story of every next door in these modern days of relationship where relations are not being respected or cared for.

When I got home that night as my wife served dinner, I held her hand and said, I’ve got something to tell you. She sat down and ate quietly. Again I observed the hurt in her eyes.
Suddenly I didn’t know how to open my mouth. But I had to let her know what I was thinking. I want a divorce. I raised the topic calmly. She didn’t seem to be annoyed by my words, instead she asked me softly, why?

I avoided her question. This made her angry. She threw away the chopsticks and shouted at me, you are not a man! That night, we didn’t talk to each other. She was weeping. I knew she wanted to find out what had happened to our marriage. But I could hardly give her a satisfactory answer; she had lost my heart to Jane. I didn’t love her anymore. I just pitied her!

With a deep sense of guilt, I drafted a divorce agreement which stated that she could own our house, our car, and 30% stake of my company. She glanced at it and then tore it into pieces. The woman who had spent ten years of her life with me had become a stranger. I felt sorry for her wasted time, resources and energy but I could not take back what I had said for I loved Jane so dearly. Finally she cried loudly in front of me, which was what I had expected to see. To me her cry was actually a kind of release. The idea of divorce which had obsessed me for several weeks seemed to be firmer and clearer now.

The next day, I came back home very late and found her writing something at the table. I didn’t have supper but went straight to sleep and fell asleep very fast because I was tired after an eventful day with Jane. When I woke up, she was still there at the table writing. I just did not care so I turned over and was asleep again.

In the morning she presented her divorce conditions: she didn’t want anything from me, but needed a month’s notice before the divorce. She requested that in that one month we both struggle to live as normal a life as possible. Her reasons were simple: our son had his exams in a month’s time and she didn’t want to disrupt him with our broken marriage.

This was agreeable to me. But she had something more, she asked me to recall how I had carried her into out bridal room on our wedding day. She requested that every day for the month’s duration I carry her out of our bedroom to the front door ever morning. I thought she was going crazy. Just to make our last days together bearable I accepted her odd request.

I told Jane about my wife’s divorce conditions. . She laughed loudly and thought it was absurd. No matter what tricks she applies, she has to face the divorce, she said scornfully.

My wife and I hadn’t had any body contact since my divorce intention was explicitly expressed. So when I carried her out on the first day, we both appeared clumsy. Our son clapped behind us, daddy is holding mommy in his arms. His words brought me a sense of pain. From the bedroom to the sitting room, then to the door, I walked over ten meters with her in my arms. She closed her eyes and said softly; don’t tell our son about the divorce. I nodded, feeling somewhat upset. I put her down outside the door. She went to wait for the bus to work. I drove alone to the office.

On the second day, both of us acted much more easily. She leaned on my chest. I could smell the fragrance of her blouse. I realized that I hadn’t looked at this woman carefully for a long time. I realized she was not young any more. There were fine wrinkles on her face, her hair was graying! Our marriage had taken its toll on her. For a minute I wondered what I had done to her.

On the fourth day, when I lifted her up, I felt a sense of intimacy returning. This was the woman who had given ten years of her life to me. On the fifth and sixth day, I realized that our sense of intimacy was growing again. I didn’t tell Jane about this. It became easier to carry her as the month slipped by. Perhaps the everyday workout made me stronger.

She was choosing what to wear one morning. She tried on quite a few dresses but could not find a suitable one. Then she sighed, all my dresses have grown bigger. I suddenly realized that she had grown so thin, that was the reason why I could carry her more easily.

Suddenly it hit me… she had buried so much pain and bitterness in her heart. Subconsciously I reached out and touched her head.

Our son came in at the moment and said, Dad, it’s time to carry mom out. To him, seeing his father carrying his mother out had become an essential part of his life. My wife gestured to our son to come closer and hugged him tightly. I turned my face away because I was afraid I might change my mind at this last minute. I then held her in my arms, walking from the bedroom, through the sitting room, to the hallway. Her hand surrounded my neck softly and naturally. I held her body tightly; it was just like our wedding day.

But her much lighter weight made me sad. On the last day, when I held her in my arms I could hardly move a step. Our son had gone to school. I held her tightly and said, I hadn’t noticed that our life lacked intimacy. I drove to office…. jumped out of the car swiftly without locking the door. I was afraid any delay would make me change my mind…I walked upstairs. Jane opened the door and I said to her, Sorry, Jane, I do not want the divorce anymore.

She looked at me, astonished, and then touched my forehead. Do you have a fever? She said. I moved her hand off my head. Sorry, Jane, I said, I won’t divorce. My marriage life was boring probably because she and I didn’t value the details of our lives, not because we didn’t love each other anymore. Now I realize that since I carried her into my home on our wedding day I am supposed to hold her until death do us apart. Jane seemed to suddenly wake up. She gave me a loud slap and then slammed the door and burst into tears. I walked downstairs and drove away. At the floral shop on the way, I ordered a bouquet of flowers for my wife. The salesgirl asked me what to write on the card. I smiled and wrote, I’ll carry you out every morning until death do us apart.

That evening I arrived home, flowers in my hands, a smile on my face, I run up stairs, only to find my wife in the bed – dead. My wife had been fighting CANCER for months and I was so busy with Jane to even notice. She knew that she would die soon and she wanted to save me from the whatever negative reaction from our son, in case we push through with the divorce.— At least, in the eyes of our son—- I’m a loving husband….

The small details of your lives are what really matter in a relationship. It is not the mansion, the car, property, the money in the bank. These create an environment conducive for happiness but cannot give happiness in themselves.

So find time to be your spouse’s friend and do those little things for each other that build intimacy. Do have a real happy marriage!

Happy Diwali to you & your family!

Festival of lights … togetherness … happiness … prosperity … sweets … celebrations … Yes Diwali is here..

A festival which is celebrated with gaiety by people of every religion. Its magical and radiant touch creates an atmosphere of joy and festivity.

With fullest of enthusiasm and excitement we all welcome this festive season together wishing Happy Diwali to you & your family.

Bid Adieu Jardine Lloyd Thompson!

Dear Friends and Colleagues,

Yesterday brought the beginning, tomorrow brings the end, and somewhere in between I acquired one of the best experiences of my life!

As some of you already know, today is my last day at JLT. Almost 15 months!!!

I have thoroughly enjoyed every aspect of my tenure here and would like to sincerely thank each JLT’ian for the experiences shared, friendships made, opportunities offered and good times spent. This has been a sojourn of both professional and personal augmentation and I am sure every time I reminisce about these days, it would bring a smile on my face.

Fate ordains that every good thing must end for another beginning. So with mixed feelings, I bid you goodbye and good luck as I move on to a new phase of my career.

Thank you,
Chirag Mehta

May all living beings grant me forgiveness … Michhami Dukkadam

On this auspicious occasion of Jain Paryushan festival, I(and my family) wish you all:

Michhami Dukkadam (My bad deeds be fruitless/forgiven)

Khaamemi Savve Jeeva (I grant forgiveness to all living beings)
Savve Jeeva Khamntu Me (May all living beings grant me forgiveness)
Metti Me Savve Bhuyeshu (My friendship is with all living beings)
Vairam Majham NA Kenai (My enemy is totally non-existent)

I forgive (from the bottom of my heart without any reservation) all living beings (who may have caused me any pain and suffering either in this life or previous lives), and I beg (again from the bottom of my heart without any reservation) for the forgiveness from all living beings (no matter how small or big to whom I may have caused pain and suffering in this life or previous lives, knowingly or unknowingly, mentally, verbally or physically, or if I have asked or encouraged someone else to carry out such activities). (Let all creatures know that) I have a friendship with everybody and I have no revenge (animosity or enmity) toward anybody.

Yours,
Chirag Mehta

Salesforce Data Storage – 2100 % Used – Whack!!!

Today I was doing data load (via some tool) and I was able to do data load of 420 MB, though my (or any) developer org allowed limit is 20 MB, Isn’t that strange!

I understand Salesforce does allow to store certain % beyond allowed limit, but this is almost 21 times allowed limit – sounds really whacky!

This is like hitting nail 21 times hard then allowed hit limit. Hope Salesforce Storage is not screaming :)