• Niranjan Reddy 19
  • NEWBIE
  • 0 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
I want to add a button to my opportunity header record that is called Insert Products. This will send the opportunity ID to a visualforce page which will have a select file button and an insert button that will loop through the CSV and insert the records to the related opportunity.

This is for non technical users so using Data loader is not an option.

I got this working using standard apex class however hit a limit when i load over 1,000 records (which would happen regularly).

I need to convert this to a batch process however am not sure how to do this.

Any one able to point me in the right direction? I understand a batch should have a start, execute and finish. However i am not sure where i should split the csv and where to read and load?

I found this link which i could not work out how to translate into my requirements:http://developer.financialforce.com/customizations/importing-large-csv-files-via-batch-apex/

Here is the code i have for the standard apex class which works.
 
public class importOppLinesController {
public List<OpportunityLineItem> oLiObj {get;set;}
public String recOppId {
        get;
        // *** setter is NOT being called ***
        set {
            recOppId = value;
            System.debug('valuevalue);
        }
    }
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}

public List<OpportunityLineItem> oppLine{get;set;}
  public importOppLinesController(){
    csvFileLines = new String[]{};
    oppLine = New List<OpportunityLineItem>();
  }
  public void importCSVFile(){

       PricebookEntry pbeId;
       String unitPrice = '';

       try{
           csvAsString = csvFileBody.toString();
           csvFileLines = csvAsString.split('\n
           for(Integer i=1;i<csvFileLines.size();i++){
               OpportunityLineItem oLiObj = new OpportunityLineItem() ;
               string[] csvRecordData = csvFileLines[i].split(',');

               String pbeCode = csvRecordData[0];
                pbeId = [SELECT Id FROM PricebookEntry WHERE ProductCode = :pbeCode AND Pricebook2Id = 'xxxx HardCodedValue xxxx'][0];                  

                oLiObj.PricebookEntryId = pbeId.Id;

               oLiObj.Quantity = Decimal.valueOf(csvRecordData[1]) ;
               unitPrice = String.valueOf(csvRecordData[2]);
               oLiObj.UnitPrice =  Decimal.valueOf(unitPrice);

               oLiObj.OpportunityId = 'recOppId';;
               insert (oLiObj);
           }
        }
        catch (Exception e)
        {

             ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR, e + ' - ' + unitPrice);

            ApexPages.addMessage(errorMessage);
        }
  }
}