Friday, January 29, 2016

Dynamically Select Objects and Import csv files in visualforce

Hi,

We can create records from visual force page from csv file. Please check the below code
You can dynamically select the object from the dropdown and upload the file. the headers should be salesforce api field names in the csv file which you are trying to load. As there is a limitation on Visualforce view state. So please load the data using dataloader if the file has more records.

Visualforce page:


   
      
      
            
                
                    
                    
                        
                    
                
            
             
{!acc[hvalues]}
Apex Class:
public class DynamicFileUploader
{
    public string nameFile{get;set;}
    public Blob contentFile{get;set;}
    public String selectedObject {get; set;}
    String[] filelines = new String[]{};
    public List<String> headervalues {get;set;}
    List<Sobject> recordstoupload;

    //get Object Name //
    public List<SelectOption> getObjectNames(){
        List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();     
        List<SelectOption> objNames = new List<SelectOption>();
        objNames.add(new SelectOption('','-- Select --'));
        for(Schema.SObjectType f : gd)
        {
           objNames.add(new SelectOption(f.getDescribe().getName(),f.getDescribe().getLabel()));
        }
        objNames.sort();
        return objNames;
    }
    
    public Pagereference ReadFile()
    {
        try{
                System.debug('\n Selected Object'+selectedObject);
                if(selectedObject == null)
                {
                    ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'Object Should be selected');
                    ApexPages.addMessage(errormsg);
                    return null;
                }
                //Convert the uploaded file which is in BLOB format into a string
                nameFile =blobToString( contentFile,'ISO-8859-1');
                
                //Now sepatate every row of the excel file
                filelines = nameFile.split('\n');
                Map<String,Schema.SObjectType> gd = Schema.getGlobalDescribe();
                Schema.SObjectType objecttypeinfo=gd.get(selectedObject);
                
                //Iterate through every line and create a Account record for each row
                recordstoupload= new List<Sobject>();
                headerValues =new List<String>();
                headerValues = filelines[0].trim().split(',');
                for (Integer i=1;i<filelines.size();i++)
                {
                    String[] inputvalues = new String[]{};
                    inputvalues = filelines[i].split(',');
                    sObject sObj = Schema.getGlobalDescribe().get(selectedObject).newSObject() ;  
                    for(Integer j=0;j<headerValues.size();j++){
                        sObj.put(headerValues[j],inputvalues[j]) ;  
                    }
                    recordstoupload.add(sObj);
                }
         }
         catch(Exception e){
                 ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured reading the CSV file'+e.getMessage());
                ApexPages.addMessage(errormsg);
         }       
        //Finally, insert the collected records
        try{
            insert recordstoupload;
        }
        catch (Exception e)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured inserting the records'+e.getMessage());
            ApexPages.addMessage(errormsg);
        }    
        return null;
    }
   
    public List<Sobject> getuploadedAccounts()
    {
        if (recordstoupload!= NULL)
            if (recordstoupload.size() > 0)
                return recordstoupload;
            else
                return null;                    
        else
            return null;
    }  

    public static String blobToString(Blob input, String inCharset){
        String hex = EncodingUtil.convertToHex(input);
        System.assertEquals(0, hex.length() & 1);
        final Integer bytesCount = hex.length() >> 1;
        String[] bytes = new String[bytesCount];
        for(Integer i = 0; i < bytesCount; ++i)
            bytes[i] =  hex.mid(i << 1, 2);
        return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
    }         
}

Labels

visualforce page ( 13 ) apex integration ( 5 ) apex trigger ( 4 ) csv file from vf page ( 4 ) javascript ( 4 ) csv visualforce page ( 3 ) Too many ( 2 ) call out ( 2 ) integration ( 2 ) rest api ( 2 ) salesforce rest api ( 2 ) salesforce to salesforce integration ( 2 ) sfdc rest api ( 2 ) trigger ( 2 ) 15 digit to 18 digit ( 1 ) DML rows in Apex ( 1 ) Date Conversion ( 1 ) Date/Time conversion ( 1 ) Deploy ( 1 ) Objects to Future Annotated Methods ( 1 ) SFDC limits ( 1 ) Sobject to Future Annotated Methods ( 1 ) Test Class ( 1 ) TimeZone Conversion ( 1 ) Too many dml rows ( 1 ) Too many future calls ( 1 ) annotations ( 1 ) apex code ( 1 ) closed opportunities ( 1 ) commit ( 1 ) convert ( 1 ) create records ( 1 ) csv create records ( 1 ) custom setting ( 1 ) deployment ( 1 ) deployment changeset ( 1 ) disable apex class ( 1 ) disable apex trigger ( 1 ) disable in production ( 1 ) document ( 1 ) download ( 1 ) field name ( 1 ) formula fields ( 1 ) iframe ( 1 ) inactive ( 1 ) intellisense ( 1 ) jsforce ( 1 ) limits ( 1 ) matrix report in vf page ( 1 ) multi select ( 1 ) multi select salesforce ( 1 ) multiselect ( 1 ) paypal ( 1 ) picklist ( 1 ) record type ( 1 ) rollback ( 1 ) salesforce limits ( 1 ) salesforce list ( 1 ) salesforce map ( 1 ) salesforce rest ( 1 ) salesforce set ( 1 ) salesforce1 ( 1 ) sandbox deployment ( 1 ) sfdc collection ( 1 ) sfdc list ( 1 ) sfdc map ( 1 ) sfdc rest ( 1 ) sfdc set ( 1 ) uncommitted ( 1 ) updated field ( 1 ) user ( 1 ) validation rule opportunity ( 1 ) validation rules opportunities ( 1 ) vf page ( 1 )

Ad