function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
HarshadaHarshada 

Getting error when trying to upload csv. This page has an error. Error happened when processing action responses [Cannot read property 'setParams' of undefined Callback failed: apex://file_upload_handler/ACTION$insertData

Component JS:
({
   /* closeModel :function(component, event, helper) {
        //  component.set('v.isOpen', false);
         var recId1 = component.get("v.recordId");
       window.location.href='/lightning/r/Account/'+recId1+'/view';
    },*/
   handleFilesChange: function(component, event, helper) {
        var fileName = 'No File Selected..';
        var ext;
        component.set('v.showSpinner', true);
        if (event.getSource().get("v.files").length > 0) {
            fileName = event.getSource().get("v.files")[0]['name'];
            ext = fileName.substring(fileName.length-3,fileName.length);
        }
        component.set("v.fileName", fileName);
        if(ext=='csv'){
            var fileInput = component.find("file").get("v.files");
            var file = fileInput[0];
            if (file) {
                var reader = new FileReader();
                reader.readAsText(file, "UTF-8");
                reader.onload = function (evt) {
                    var csv = evt.target.result;
                    window.setTimeout($A.getCallback(function(){
                        helper.FetchData(component,csv);
                    }), 10);
                }
                reader.onerror = function (evt) {
                }
            }
        }
        else {
            component.set("v.errorMessage",'Kindly select a CSV file.');
            component.set('v.showSpinner', false);
        }
    },


   showAlert : function(component, event, helper) {
     alert('Test Alert');
    }

})
*******************************************************************************
Component helper:
({
    FetchData : function (component,csvData){
          var recId1 = component.get("v.recordId");
      
       // var fname = component.get("v.fileName");
        var recId = component.get("v.recordId");
        var action = component.get("c.insertData");
        action.setParams({
            "strfromlex" : csvData,
           // "recordId"  : recId
           // "FileName"  : fname
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {  
                var rtnValue = response.getReturnValue();
             //If there is no error in csv file simply show success message
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    title : 'Success',
                    message: 'File Uploaded Successfully.',
                    duration:'5000',
                    key: 'info_alt',
                    type: 'success',
                    mode: 'sticky'
                });
                toastEvent.fire();
                  $A.get('e.force:refreshView').fire();
                component.set('v.showSpinner', false);
                 window.location.href='/lightning/r/Account/'+recId1+'/view';
               // component.set('v.isOpen', false);
                }
 else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                   // alert(errors);
                    var toastEvent = $A.get("e.force:showToast");
                    toastEvent.setParams({
                        title : 'Error',
                        message:'There were failures while file upload, please check related records.',
                        duration:' 5000',
                        key: 'info_alt',
                        type: 'error',
                        mode: 'sticky'
                    });
                    toastEvent.fire();
                    component.set('v.showSpinner', false);
            }
        }
*******************************************************************************
Vf page:
<apex:page standardController="Account"  recordSetVar="accounts" tabStyle="account" lightningStylesheets="true">
    <apex:includeLightning />
    <div id="lightning">
        
    </div>
    
<script>
 $Lightning.use("c:AccountCsvFileUploadApp", function() {
 $Lightning.createComponent("c:AccountCsvFileUpload",{
 },
                            
"lightning", 
                            
     function(component){
         // component.set('v.isOpen',true);
        component.set("v.strfromlex");
         component.set("v.recordId");
         component.set("v.fileName", fileName);
 });
 });
 </script>
</apex:page>
*******************************************************************************

       
 
HarshadaHarshada
CLASS:

public class file_upload_handler {
    
    // To read the csv file data , RecordId of Account and File Name
    @AuraEnabled
    public static void insertData(Blob strfromlex,Id recordId){
        
        // String storeAllProducts='';
        Map<String,List<String>> oppnametoProdlist = new Map<String,List<String>>();
        
        Map<String,List<String>> newMap = new Map<String,List<String>>();
        
        //Map<string,id> oppnametoid=new Map<string,id>();
        Set<String> oppname=new Set<string>();
        Map<id,String> oppTocur = new  Map<id,String>();
        
        map<id,id> mapProductPricebookentryid = new map<id,id>();
        List<Opportunity> oppLst = new List<Opportunity>();
        //To map Opportunity name and Product Name
        map<string,string> mapOppnameProdName = new map<string,string>();
        //To map Product name and Product Id
        map<string,string> mapProdNameId = new map<string,string>();
        //To map Product Id and Opportunity name 
        map<string,string> mapProdIdName = new map<string,string>();
        // To map Sales Person Name and Id
        map<string,id> mapSalesNameId = new map<string,id>();
        // To list the Product Names/Material_code
        List<String> prodName = new List<String>();
        // List the Sales Person Names
        List<String> salesPerName = new List<String>();
        List<Product2> prodId = new List<Product2>();
        
        // 
        Map<String,String> oppNametoPurId= new Map<String, String>();
        Map<String,String> purNametoPurId= new Map<String, String>();
        List<String> prodnumber = new List<String>();
        // List Purchaser's Name
        List<String> purName = new List<String>();
        // List Purchaser's Email
        List<String> emailID = new List<String>();
        // List Purchaser's Contact No
        List<String> contNo = new List<String>();
        // List of Purchasers Account
        List<Account> accPurList = new List<Account>();
        //List of customer number
        List<String> CustomerNo = new List<string>();
        //List of Account ID
        list<string> AccId = new list<string>();
        //List of Opportunity 
        list<ID> op5 = new list<id>();
        
        
        
        
        
        Id RFQRecIdOpp = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('RFQ').getRecordTypeId();
        // system.debug('RFQRecIdOpp--> '+RFQRecIdOpp);
        Id soldToRecId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Export').getRecordTypeId(); // Changed to Export(prev Sold To)
        system.debug('soldToRecId-->'+soldToRecId);
        List<OpportunityLineItem> OLILst = new List<OpportunityLineItem>();
        
        // Convert CSV file data into String Format
        String fileData =strfromlex.toString();  
        
        // To split rows of csv files
        String[] csvFileLines = new String[]{};
            csvFileLines = fileData.split('\n'); 
        system.debug('csvFileLines.size() --'+csvFileLines.size());
        // To get Sales Person Names from CSV
        String[] inputvalues3 = new String[]{};
            for(Integer k=1;k<csvFileLines.size(); k++ ){
                inputvalues3 = funSplitter(csvFileLines[k]);
                system.debug('inputvalues3 '+inputvalues3.size());
                
                if(inputvalues3.size()>0){
                    salesPerName.add(inputvalues3[5]);
                    system.debug('inputvalues3[5]' +inputvalues3[5]);
                    CustomerNo.add(inputvalues3[24]);
                     system.debug('inputvalues3[24]' +inputvalues3[24]);
                    purName.add(inputvalues3[2]);
                    emailID.add(inputvalues3[3]);
                    contNo.add(inputvalues3[4]);
                    oppNametoPurId.put(inputvalues3[20],inputvalues3[2]);
                    //   prodnumber.add(inputvalues3[10]);
                }
            }
        system.debug('oppNametoPurId -->'+oppNametoPurId);
        
        // Check Purchaser's record is created, if not create new record
        if(!CustomerNo.isempty()){
            accPurList = [Select Id,Name
                          from Account
                          where Customer_No__c In : CustomerNo];
            
            if(accPurList.isEmpty()){
                for(Integer p=0;p<purName.size();p++){
                    Account accPur = new Account();
                    accPur.RecordTypeId = soldToRecId; 
                    accPur.Name = purName[p];
                    accPur.Purchaser_s_Email_ID__c = emailID[p];
                    accPur.Purchaser_s_Contact_No__c = contNo[p];
                    accPurList.add(accPur);
                }
                
                if(accPurList.size()>0){
                    insert accPurList;
                }
            }
            system.debug('size-->'+accPurList.size());
            for(Account ac1 : accPurList){
                purNametoPurId.put(ac1.Name,ac1.Id);
                AccId.add(ac1.Id);
                
            }
            system.debug('purNametoPurId--> '+purNametoPurId);
            
            /* List<Account> aId = [Select Id from Account
where Customer_No__c In : CustomerNo];
//List<Id> AccId = new List<Id>();
for(Account ac2 : aId){

AccId.add(ac2.id);
}
*/
        }
        
        
        //}
        
        // To get the Id's of Sales person and store in Map
        if(!salesPerName.isempty()){
            List<User> userList = [SELECT Id,
                                   Name 
                                   FROM User 
                                   WHERE Name IN :salesPerName];
            
            if(!userList.isempty()){
                for(User U: userList){
                    mapSalesNameId.put(U.name,U.Id);
                }
            }
        }
        
        Pricebook2 standardPricebook = [select id,Name from pricebook2 where Name=:'Standard price book'];
        //  update standardPricebook;
        system.debug('standardPricebook---->'+standardPricebook);
        Integer n=0;
        List<String> prodlst= new List<String>();
        // To read the CSV files data and map to respective fields
        for(Integer i=1, j=csvFileLines.size()-1; i<=j; i++ ){
            
            String[] inputvalues = new String[]{};
                
                // To split the columns of a row
                inputvalues = funSplitter(csvFileLines[i]);
            system.debug('inputvalues size -->'+inputvalues.size());
            system.debug('inputvalues  -->'+inputvalues);
            
            if(inputvalues.size()>0){
                // To insert Opportunity record
                for (integer x=0;x<AccId.size();x++){
                Opportunity opp = new Opportunity();
                opp.RecordTypeId =RFQRecIdOpp;// '0120k000000PUGYAA4';
                opp.Purchaser_s__c = purNametoPurId.get(oppNametoPurId.get(inputvalues[20])); // accPurList[n].Id; 
                opp.AccountId = AccId[x];
                opp.Name = inputvalues[20];
                system.debug('inputvalues[21] '+inputvalues[21]+' '+opp.Name );
                system.debug('inputvalues[23] '+inputvalues[23] );
                opp.StageName =inputvalues[21];
                opp.Probability__c =inputvalues[22];//Double.valueOf(inputvalues[23]);
                opp.CloseDate =Date.parse(inputvalues[23]);
                opp.RFQ_Receipt_Date__c =inputvalues[0];//Date.parse(inputvalues[0]);
                opp.Validity__c = inputvalues[1];
                opp.Purchaser_s_Email_ID__c =inputvalues[3];
                opp.Purchaser_s_Contact_No__c =inputvalues[4];
                
                
                opp.Country__c = inputvalues[7];
                opp.Region__c = inputvalues[8];
                opp.Product_Group__c =inputvalues[9];
                
                opp.Delivery_Location_1__c = inputvalues[11];
                opp.Packing_1__c = inputvalues[12];
                opp.MOQ_in_MT__c =Double.valueOf(inputvalues[13]);
                opp.Dispatch_Location__c  = inputvalues[14];
                opp.CurrencyIsoCode =inputvalues[15];
                
                opp.Last_Contract_Price__c  = Double.valueOf(inputvalues[16]);
                opp.New_Proposal__c = Double.valueOf(inputvalues[17]);
                opp.RFQ_Volume__c =Double.valueOf(inputvalues[18]); //5
                opp.Volume_Allocated__c   =Double.valueOf(inputvalues[19]);
                // opp.Pricebook2Id='01s0k000000T1mIAAS';
                opp.Pricebook2Id=standardPricebook.Id;
                // map of opp name t product name
                mapOppnameProdName.put(inputvalues[20],inputvalues[25]);
                System.debug('mapOppnameProdName '+mapOppnameProdName);
                oppname.add(opp.name);
                
                // New approach --> Add all products material code in one string
                String storeAllProducts='';
                for(Integer m=25;m<inputvalues.size();m++){
                    storeAllProducts = storeAllProducts + inputvalues[m] +',';
                }
                opp.All_Products_From_CSV__c = storeAllProducts;
                system.debug('storeAllProducts->'+storeAllProducts);
                //storeAllProducts ='';
                oppLst.add(opp);
                n++;
                 }
            }
        }
        system.debug('oppLstsize->'+oppLst.size());
        system.debug('oppLst->'+oppLst);
        
        if(oppLst.size()>0){
            insert oppLst;
            system.debug('Inserted opp');
            
        }
    }
    
    
    
    // Called this method fro trigger
    public static void addProd(Id oppId){
        system.debug('In method');
        List<OpportunityLineItem> OLILst = new List<OpportunityLineItem>();
        map<id,id> mapProductPricebookentryid = new map<id,id>();
        Opportunity opp=[select id,name,All_Products_From_CSV__c,CurrencyIsoCode from Opportunity where Id = : oppId];
        List<string> materialcodeList = new List<String>();
        if(opp.All_Products_From_CSV__c != Null){
            List<String> lst2 = new List<String>();
            lst2 = opp.All_Products_From_CSV__c.split(',');
            for(String s2 : lst2){
                materialcodeList.add(s2);
            }
        }
        
        List<Product2> prodId = new List<Product2>();
        List<Pricebook2> pricebook = new List<Pricebook2>();
        prodId = [select Id,Material_Code__c,Name from Product2 where Material_Code__c  IN :materialcodeList ];
        system.debug('prodId-> '+prodId);
        pricebook = [select Id , name from Pricebook2 where IsActive = true and Name=:'Standard Price Book' ];
        System.debug('book--->'+pricebook);
        
        for(Product2 prod : prodId){
            for(Pricebook2 book : pricebook){
                PricebookEntry priceBookEntry = [SELECT Id, 
                                                 Product2Id, 
                                                 Pricebook2Id 
                                                 FROM PricebookEntry
                                                 WHERE Pricebook2Id =: book.Id  and Product2Id =: prod.id 
                                                 and CurrencyIsoCode =: opp.CurrencyIsoCode
                                                 and IsActive = true
                                                 // OR CurrencyIsoCode=:'EUR' OR CurrencyIsoCode=:'GBP')
                                                ];
                
                System.debug('priceBookEntry '+priceBookEntry);
                mapProductPricebookentryid.put(priceBookEntry.Product2Id,priceBookEntry.id);
                System.debug(mapProductPricebookentryid);
            }
        }
        for(Product2 prodlst : prodId){
            system.debug('hello');
            OpportunityLineItem oppLineItem = new OpportunityLineItem();
            oppLineItem.OpportunityId = opp.id;
            oppLineItem.PricebookEntryId = mapProductPricebookentryid.get(prodlst.Id);
            system.debug('hello');
            oppLineItem.Product2Id =prodlst.Id;
            oppLineItem.Quantity = 1;
            oppLineItem.TotalPrice = 1;
            OLILst.add(oppLineItem);
        }
        
        system.debug('OLILst-->'+OLILst.size()+'  data-->'+OLILst);
        if(OLILst.size()>0){
            insert OLILst;
        }
        opp.All_Products_From_CSV__c = '';
        update opp;
        system.debug('updated');
    }
    
    // To split the column data of a row
    
    @AuraEnabled
    public static List<String> funSplitter(String str){
        List<String> lstFinal = new List<String>();
        Set<String> setQuotedText = new Set<String>();
        string s1 = str.trim();
        String[] strSplitted = s1.split('"');
        for (integer i = 1; i < strSplitted.size(); i += 2) 
        { 
            setQuotedText.add(strSplitted[i]);
        }
        for (integer i = 0; i < strSplitted.size(); i++ ) 
        { 
            String str1 = strSplitted[i];
            String s = str1.trim();
            String str2 = s.trim().removeEnd(',');
            String str3 = str2.removeStart(',');
            if(str3.length() > 0)
            {
                if(setQuotedText.contains(str3))
                {
                    lstFinal.add(str3);
                }
                else
                {
                    List<String> lst2 = new List<String>();
                    lst2 = str3.split(',');
                    for(String s2 : lst2){
                        lstFinal.add(s2);
                    }
                }
            }
        }
        system.debug('lstFinal -->'+lstFinal.size()+' data -->'+lstFinal);
        return lstFinal;
    }
    
}
Maharajan CMaharajan C
Hi Harsha,

You are missing to enqueue the Server side action:  

        $A.enqueueAction(action); ==> This Statement is missing in the FetchData Method:

({
    FetchData : function (component,csvData){
          var recId1 = component.get("v.recordId");
      
       // var fname = component.get("v.fileName");
        var recId = component.get("v.recordId");
        var action = component.get("c.insertData");
        action.setParams({
            "strfromlex" : csvData,
           // "recordId"  : recId
           // "FileName"  : fname
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {  
                var rtnValue = response.getReturnValue();
             //If there is no error in csv file simply show success message
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    title : 'Success',
                    message: 'File Uploaded Successfully.',
                    duration:'5000',
                    key: 'info_alt',
                    type: 'success',
                    mode: 'sticky'
                });
                toastEvent.fire();
                  $A.get('e.force:refreshView').fire();
                component.set('v.showSpinner', false);
                 window.location.href='/lightning/r/Account/'+recId1+'/view';
               // component.set('v.isOpen', false);
                }
 else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                   // alert(errors);
                    var toastEvent = $A.get("e.force:showToast");
                    toastEvent.setParams({
                        title : 'Error',
                        message:'There were failures while file upload, please check related records.',
                        duration:' 5000',
                        key: 'info_alt',
                        type: 'error',
                        mode: 'sticky'
                    });
                    toastEvent.fire();
                    component.set('v.showSpinner', false);
            }
        }
            });
            $A.enqueueAction(action);         ///  It's Required here

}
})

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/controllers_server_actions_call.htm

Thanks,
Maharajan.C