Migrating Opportunity line item

This post is a continuation of my earlier post on Product, Pricebook and Pricebook entry.Opportunity Product(line item) is a junction object between opportunity and pricebookentry table.List of fields in opportunity products

  • ID

Fields indicated in red are mandatory fields and fields which are in grey are read only. Unit price field specifies the price at which the product was sold. List price is the price of the product in the pricebook. use either one of the totalprice or unitprice field while loading.The other field will be automatically calculated based on quantity while loading. Refer to my previous post for inserting a new pricebook entry/ Exporting existing pricebookentry. Prepare a csv file with all these data.Also optional fields like service date and description can be filled for CSV. Use data loader to insert data. Click here for Sample CSV

Notes on loading

  • pricebook entry should be in the same pricebook that is assigned to the opportunity.  The pricebook name can be found in pricebook2id field in opportunity
  • If the opportunity does not have an associated pricebook2, the API automatically sets the pricebook on the opportunity if the line item corresponds to a Pricebookentry in an active Pricebook2. Changing the pricebook association would delete existing opportunity line items.
  • Creating an OpportunityLineItem increments the OpportunityAmount value by the TotalPrice of the OpportunityLineItem. Additionally, inserting an OpportunityLineItem increments the ExpectedRevenue on the opportunity by the TotalPrice times the opportunity Probability.
  • The OpportunityAmount becomes a read-only field when the opportunity has line items.
  • If multi-Currency is enable for your organization, Choose a price book that contains products with the same currency as the opportunity. pricebook entry currency code should match opportunity currency code.You cannot update the CurrencyIsoCode field on the opportunity if line items exist.

Escalation Queues and workflows

I recently had a need to escalate a case which has status value new and in a queue for 2 hours, So that if nobody picks up the case it would be escalated to manager.It took me about a day to figure out how to write the entry criteria to check whether the case is in a queue or assigned to a owner. salesforce Ids has a certain pattern across all org for certain objects. so by that i figured out that users always started with 005 and group and queue always started with 00G.

Also i had to use ‘Formula evaluates to true’  instead of easy ‘Criterias are met’ as owner ids are not available in this. Here is the formula i used.

AND(  ISPICKVAL( Status ,”New”) , BEGINS(OwnerId, “00G”) ,not( IsClosed ) )  

 Now coming to other stuffs
Realized that Case Escalation cannot trigger a workflow. Case escalation would cause an ‘isEscalated’ flag to be checked. I assumed that it can be used to trigger a workflow. i used the same entry criteria in workflow as in the escalation rule and used time dependent action instead. Thankfully my use case needed field updates only for the first time the case is escalated.

Couple of more things changes to formulae field would not trigger the workflow and so also field update from a workflow. This link might be useful Workflow considerations

If you could find if salesforce has documented somewhere which all will trigger a workflow, Let me know 

Loading Converted Leads

      When you are migrating data from one system to another there will be a need to load the leads as converted as they would have been already converted in the source system.    First step is to raise the case with salesforce.com to open up the audit fields for your organisation. The fields CONVERTEDACCOUNTID, CONVERTEDCONTACTID, CONVERTEDOPPORTUNITYID and CONVERTEDDATE will not be visible while inserting or updating by default.

Once the salesforce allows you to load these system fields you can start your process.

Steps for Loading

  • Firstly, Load Account, Contact and Opportunity which needs to be associated with the converted lead.
  • Next prepare a csv files with information of lead and get the ids from previous step and load it into the appropriate converted fields of file as mentioned above.
  • The field Isconverted should be set to true
  • Insert, Update or Upsert the leads as necessary.

Things to consider while loading

  • Converted Account is mandatory . Converted contact and opportunity is not mandatory. converted contact and opportunity need not belong to converted account.
  • You cannot see the information of converted leads. If you go to the lead detail page through its id you will see information on Converted date, Converted account, Contact and opportunity whichever was mapped. Only way to extract the information is through API
  • Lead conversion mapping will not be respected.For eg Lead description is mapped to contact description and when u load the converted lead with description it will not be carried over to the converted contact.
  • Converted date if not mapped will give value This lead was converted on {0} on lead detail page. If you need to enter converted date make sure you also enter created date . Otherwise it would error out as created date would be defaulted to now which will be at future date when compared to converted date.
  • Lead triggers and validation rules will be fired.
  • Converted Leads cannot be updated but can be deleted

click here to have a look at the sample csv file.

If you have any questions please post it in comments section

Rendering VF page as pdf and sending pdf as an attachment from a list view

Thought i would share something which i needed to work on. I thank Jeff Douglas for his awesome post which helped me in this assignment.Requirement

    There is a custom visualforce page which is rendered as pdf. There is a button on contact detail page which when clicked would call this vf page. These things were present. In addition to viewing this pdf from contact detail there was also a necessity to email these PDFs that too in bulk from list views.
list button was created with source as VF page.
Controller is where all the code is
public  class emailcontact {
     public ApexPages.StandardSetController propcontroller{get;set;}
    public list props{get;set;}  
    public emailcontract(ApexPages.StandardSetController controller) {
    propcontroller =(ApexPages.StandardSetController)controller;   
    public pagereference sendingemail(){
        props = propcontroller.getSelected();// Contains the list of record which is selected from the list  
        PageReference pdf = Page.VFpagetoberenderedaspdf;
        for(contact pr : props)
            attachment attach = new attachment();
            Blob body;
            try {
                body = pdf.getContentAsPDF();
            catch (VisualforceException e) {
                body = Blob.valueOf(‘Missing Text’);
            // ********************* for attachment to the contactrecord ******************************   
            attach.Body = body;        
            attach.Name = ‘Contact’ +system.today+’.pdf’;
            attach.IsPrivate = false;
            attach.ParentId = pr.Id;
            catch(exception e)
            // ************************ for email creation************************************   
            Messaging.EmailFileAttachment attach2 = new Messaging.EmailFileAttachment();
            attach2.Body = body;
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {pr.Email};
            mail.setSubject(‘Offer for’ + pr.name);// alternatively use templates as well
            mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach2 });
            mail.setHtmlBody(‘Please find attached a cash offer for your listing at ‘);           
    if(att!= null)
    insert att;
    if(em_sent != null)
    pagereference pr  = new pagereference(‘/a0e/o’);//will redirect to contact tab
    return pr;
Also you can add a piece of code to send an email to yourself to indicate the success or failure of the action or display it in the page
Major limitation i faced is no of the records the code can process (Governor limits on callouts). It was limited to 10 after which time out error happened. I tried using batch as well as future calls. Both returned me empty PDFs. Waiting for Salesforce to remove these limitations in future.

Setting a child record to play a unique primary role to parent through config

There are many use cases where there is need to set one of the child record as primary and when another child record is updated as primary it should throw up an error saying that primary record already exists (similar to contact roles function). Many of  the developers would suggest an apex trigger solution But this can be achieved through configuration alone.Its a simple 2 step process.

  1. Create a Roll up summary field on the parent object. It would roll up the count of the child records which have the primary checkbox set to true.


  • Create a validation rule on this field if the number becomes more than 1 validation error will be thrown.



U are good to go now. When the child record is updated to primary rollup would happen. But when there is a primary record rollup will try to become 2 triggering the validation error thus preventing it from saving the record. But if the relationship between child and parent is lookup or u want user to be pointed to the primary record in the error message listen to developers 🙂

List of items that cannot be deployed in salesforce

Recently when I was deploying configuration for an org which has not gone live, into UAT I made note of manual tasks as i need to reuse that for deploying from UAT to production. I thought i will add few more items on the list to the list i already had. These items had to be manually configured and cannot be deployed.

  •  Renaming Standard fields labels
  • Deletion of Picklist values
  • Configuring Search Layouts for all standard objects
  • Escalation rules and Assignment rules
  • Quote Templates

Always as a golden rule Deploy anything with profiles as all the necessary permissions will be carried over.

Salesforce and WSSE security headers

I wanted to name this post as WSSE security header or How i lost my war with the webservice team much like this movie (If you have not watched this i would strongly recommend to watch it).

The requirement looked pretty straight forward consume wsdl , send the request and handle the response. But we faced the issue of WSSE headers. It looks something like this

user@email.com *********
The WSDL did not have the header part . So while sending request the above header was not present. The first approach we took was if it was possible for webservice team to support httpheaders instead of soap header. It was denied immediately.

The next step was to code the header into the generated apex class. It is bit tricky and involves extensive understanding of  WSDL2APEX functionality

Prevent inserting duplicate records without coding!!!

Hi Friends,Today implemented this simple technique to prevent inserting  duplicate records ( records with same name)

In one of my customer’s org… there was a trigger written on a campaign object to prevent inserting campaign with same name…some developer wrote it few months back… though its a simple trigger but there was a logical bug in it…. however when our system admin informed me about this issue….i thought of the following solution:-

1- Create a new text field called “custom_name__c”
2- Check “Unique(do not allow dups)” checkbox while you are creating this field
3- Create a workflow rule that updates this field with the standard name field of the object every time record is inserted or updated…..

simple right?????
 so there is no need of that trigger anymore!!!!!!!!!!!1 🙂

Modal dialog in VisualForce page using Jquery




  null}" >


  null}" >




  var x = JobShiftDateTimeString('{!shift.Start_Date_Time__c}', '{!shift.Duration__c}'); 
 OpenSignUpDlg('{!job.Id}', '{!shift.Id}', '{!JSENCODE(job.Name)}', x); 
 return false;"




styleClass=”{!IF(f.Type == ‘Long Text Area’, ‘cssInputFields cssTextArea’, ‘cssInputFields’)}” />

styleClass=”{!IF(f.Type == ‘Long Text Area’, ‘cssInputFields cssTextArea’, ‘cssInputFields’)}” />

immediate=”false” status=”statusSignUp” />