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
RakeebRakeeb 

Scenario?

Hi,I have one scenario like i want to upload the  csv file (csv contains same fields in custom object)and insert in to custom objects using apex coding how can i do that ?without using dataloader and import wizard.Suppose if it is not possible in apex ,otherwise if you know any app in appexchange kindly let me know the solution asap.

bob_buzzardbob_buzzard

Here's a blog post (not mine!) that shows how to do this using apex/visualforce:

 

http://www.ericsantiago.com/eric_santiago/2011/03/upload-and-parse-csv-via-visualforce.html

RakeebRakeeb

Thanks a lot ,when i am uplaoding the csv file then it will populate on Visual force page up to this ok.But csv file data i want to store in to custom object how can i do that kindly let me know asap.

bob_buzzardbob_buzzard

Once you have parsed the CSV file, you can do whatever you like with the data - in your case you'd traverse the rows and create a custom object per row.

RakeebRakeeb

Thanks,As per the above apex code, where i can use the custom object so that i can map the fields and parse in to custome object. Kindly let me know AsAP.

bob_buzzardbob_buzzard

You'd need to change the getResults method.  Rather than being a getter, this would probably be an action method that is invoked from a button press or similar.

 

Rather than:

 

 for (List<String> row : parsedCSV){
        if (row.size() > colCount){
             colCount = row.size();
        }
 }

 

You'd want something like:

 

 

List<My_Custom__c> recs=new List<My_Custom__c>();
Integer rowCount=0;
for (List<String> row : parsedCSV)
{
    if (0==rowCount)
    {
         // store this list of strings as the field headers
    }
    else
    {
       My_Custom__c rec=new My_Custom__c();
       recs.add(rec);
       for (String col : row)
       {
          // based on the header information extracted above,
          // get the name of the field and store in fieldName
          rec.put(fieldName, col);
       }
    }
}

insert recs;

 

RakeebRakeeb

Thanks,Here i have custom object called 'Sales_Claim__c' and the fields are 'Quarter__c,Reseller__c'Status__c and asper the above code i have modified as fallows List<Sales_Claim__c> recs=new List<Sales_Claim__c>(); Integer rowCount=0; for (List<String> row : parsedCSV) { if (0==rowCount) { // store this list of strings as the field headers } else { Sales_Claim__c rec=new Sales_Claim__c(); recs.add(rec); for (String col : row) { // based on the header information extracted above, // get the name of the field and store in fieldName rec.put(Quarter__c, col); rec.put(Reseller__c, col);rec.put(Status__c, col); } } } insert recs; Is this correct?and i am getting error like 'Compile Error: Invalid identifier: Quarter__c' kindly let me know the sol asap

bob_buzzardbob_buzzard

It won't work as I posted - the items in the comments are for you to implement.  But hopefully you guessed that.

 

You need to put your field names in quote marks:

 

rec.put('Quarter__c', col);

 If you know the order of fields and that's not going to change, you can simply pluck out the fields at the positions.

 

E.g.

 

    My_Custom__c rec=new My_Custom__c();
    recs.add(rec);
    rec.put('Quarter__c', row[0]);
    rec.put('Reseller__c', row[1]);
    rec.put('Status__c', row[2]);

 

RakeebRakeeb

Thanks,I have declared as public for custom fields i.e public String Quarter__c;
        public String Reseller__c;
        public String Status__c; 

     even though i am getting error like ' Compile Error: Invalid identifier: Quarter__c ' Kindly let me know the sol asap.

bob_buzzardbob_buzzard

Why are you using properties for these values?  I thought you wanted to add them to the custom object that you were creating?

RakeebRakeeb

Thanks,when i am uplaoding in to custom object but insert method is not working and i am getting error like"System.LimitException: DML currently not allowed
Class.uploadCSVcontroller.getResults: line 54, column 22 External entry point " kindly let me know the solution asap.

bob_buzzardbob_buzzard

Have you changed the method name from a getter?  I don't think Apex will like DML in a get method.

RakeebRakeeb

Thanks, I didn't change any thing in properties.kindly check this below code and vf page is same as in the above link

public class uploadCSVcontroller {

        public Blob contentFile { get; set; }
        public String nameFile  { get; set; }
        public Integer rowCount { get; set; }
        public Integer colCount { get; set; }
     
      
      
        public List<List<String>> getResults() {
           
            List<List<String>> parsedCSV = new List<List<String>>();
           
          
            rowCount = 0;
            colCount = 0;
            if (contentFile != null){
                String fileString = contentFile.toString();
                parsedCSV = parseCSV(fileString, false);
                System.debug('parsedCSV:'+parsedCSV);
                rowCount = parsedCSV.size();
                System.debug('RowCount:'+rowCount);
             
                List<Sales_Claim__c> recs=new List<Sales_Claim__c>();
                Integer rowCount=0;
               
                 for (List<String> row : parsedCSV)
                  {
                   Sales_Claim__c rec=new  Sales_Claim__c();
                   System.debug('REC:'+rec);
                   recs.add(rec);
                   System.debug('recs1:'+recs);
                   for (String col : row)
                   {
                                   
                     rec.put('Quarter__c', row[0]);
                     System.debug('QA:'+row[0]);
                     rec.put('Reseller__c', row[1]);
                     rec.put('Status__c', row[2]);
                    }
                   }
                    
                     insert recs;
                    
            }
            return parsedCSV;
        }

      
        public static List<List<String>> parseCSV(String contents,Boolean skipHeaders) {
            List<List<String>> allFields = new List<List<String>>();
            contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
            contents = contents.replaceAll('""','DBLQT');
            System.debug('contents:'+contents);
            List<String> lines = new List<String>();
            try {
              
                lines = contents.split('\r');
             
            } catch (System.ListException e) {
                System.debug('Limits exceeded?' + e.getMessage());
            }
            Integer num = 0;
            for(String line: lines) {
                 if (line.replaceAll(',','').trim().length() == 0) break;
                 List<String> fields = line.split(',');
                List<String> cleanFields = new List<String>();
                String compositeField;
                Boolean makeCompositeField = false;
                for(String field: fields) {
                    if (field.startsWith('"') && field.endsWith('"')) {
                        cleanFields.add(field.replaceAll('DBLQT','"'));
                    } else if (field.startsWith('"')) {
                        makeCompositeField = true;
                        compositeField = field;
                    } else if (field.endsWith('"')) {
                        compositeField += ',' + field;
                        cleanFields.add(compositeField.replaceAll('DBLQT','"'));
                        makeCompositeField = false;
                    } else if (makeCompositeField) {
                        compositeField +=  ',' + field;
                    } else {
                        cleanFields.add(field.replaceAll('DBLQT','"'));
                    }
                }
              
                allFields.add(cleanFields);
            }
            if (skipHeaders) allFields.remove(0);
            System.debug('allFields:'+allFields);
            return allFields;
                
        }

    }

 

But i am getting error like "System.LimitException: DML currently not allowed
Class.uploadCSVcontroller.getResults: line 54, column 23 External entry point " Kindly let me know the sol asap

bob_buzzardbob_buzzard

That is because you are using result in the page as a property which is backed by the getResult method.  DML is not allowed in getters as they are called multiple times.

 

You'll need to change this to an action method which is called when the user clicks an upload button or similar.

RakeebRakeeb

Thanks,So instead of that what can i use?kindly let me know asap.

bob_buzzardbob_buzzard

You would use an action method.  And you would invoke that action method from a commandbutton.

RakeebRakeeb

Thanks bob,when i am providing as shown below i.e instead of getResults()

 public List<List<String>> Results() {

return parsedCSV;

}

page:

<apex:commandButton value="Upload" action="{!Results}" id="theButton"/>

when i saved the page i am getting this error as shown below.System.DmlException: Insert failed. First exception on row 0; first error: MALFORMED_ID, Reseller: id value of incorrect type: Quarter__c: [Reseller__c]
Class.uploadCSVcontroller.Results: line 54, column 22 External entry point .

Kindly let me know the solution asap

 

bob_buzzardbob_buzzard

This looks like you aren't mapping your fields correctly - you've used a reseller where the field is a lookup to a quarter or vice versa.

RakeebRakeeb

Thanks a lot for giving a solutions and to resolved such kind of complex task.Once again thanks bob....

RakeebRakeeb

Hi bob,as per the above code i want do some validations before updating the records in Sales_Claim__c.i have reseller__c object in that i have reseller_name_c and region_c and category_c.But my condition is 'Select Reseller_Region__c, Name, Id From Reseller__c where Reseller_category__c NOT IN('Distributor(T1)')' based on this condition i have to update the records in Sales_Claim__c.Where can i do the validation in the above code, kindly give me the example as per the above code.

bob_buzzardbob_buzzard

You'd need to add the validation in at the point that you create the new record, but before you have added it to the list of records to insert.

RakeebRakeeb

Thanks,My scenarieo :when i am uploading csv file in to custom object first it will check whether the data is existing r not .If it is exist then i have to update the records otherwise it will perform insert operation.As per the above code it will perform only insert operation.Here i want to do validation before updating the records in Sales_Claim__c.Before updating the records i have to check in reseller__c object ,in that i have reseller_name_c and region_c and category_c.But my condition is 'Select Reseller_Region__c, Name, Id From Reseller__c where Reseller_category__c NOT IN('Distributor(T1)')' based on this condition i have to update the records in Sales_Claim__c object.Where can i do the validation in the above code, kindly give me the example as per the above code.Kindly let me know asap.

RakeebRakeeb

Hi bob,i hope u have understood my scenario still If your not getting kindly let me know.i will tell you once again.

bob_buzzardbob_buzzard

I'm still not quite understanding you, so I'll need to step through.  Are you inserting Reseller__c objects or is this a field in your Sales_Claim__c object?