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
Sarma DuvvuriSarma Duvvuri 

List of Records and want to save to account object

Hi All,

I have imported the list of accounts in CSV formate in visualforce page. i have 2 tasks.
1. I want to upload only 5 account records if it is more than 5 it should show the error message
2. What are the records i got in visual force page should save in account object once i click on save button in visual force page. please suggest.

code is below..

VisualforcePage:
<apex:page controller="importDataFromCSVController">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock >
            <apex:pageBlockSection > 
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Upload" action="{!importCSVFile}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
           <apex:pageblocktable value="{!accList}" var="acc">
              <apex:column value="{!acc.name}" />
              <apex:column value="{!acc.AccountNumber}" />
              <apex:column value="{!acc.Type}" />
              <apex:column value="{!acc.Accountsource}" />
              <apex:column value="{!acc.Industry }" />
        </apex:pageblocktable>
     </apex:pageBlock>
   </apex:form>
</apex:page>

Apex class:
public class importDataFromCSVController {
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public List<account> acclist{get;set;}
  public importDataFromCSVController(){
    csvFileLines = new String[]{};
    acclist = New List<Account>(); 
  }
  
  public void importCSVFile(){
       try{      
        
           csvAsString = csvFileBody.toString();
           csvFileLines = csvAsString.split('\n'); 
            
           for(Integer i=1;i<csvFileLines.size();i++){
               Account accObj = new Account() ;
               string[] csvRecordData = csvFileLines[i].split(',');
               accObj.name = csvRecordData[0] ;             
               accObj.accountnumber = csvRecordData[1];
               accObj.Type = csvRecordData[2];
               accObj.AccountSource = csvRecordData[3];   
               accObj.Industry = csvRecordData[4];                                                                             
               acclist.add(accObj);   
           }
        //insert acclist;
        }
        catch (Exception e)
        {
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'Please upload the csv format file');
            ApexPages.addMessage(errorMessage);
        }  
  }
}




 
Ajay K DubediAjay K Dubedi
Hi Sarma,

First,to uncomment insert acclist to save record in Account object;
1-you need to a csv file account record less than or equal to 5 to check insert record in Account Object.
2-you need to a csv file account record more than 5 to check error.
Your problem has been solved.

VisualforcePage:
<apex:page controller="importDataFromCSVController">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock >
            <apex:pageBlockSection > 
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Upload" action="{!importCSVFile}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
           <apex:pageblocktable value="{!accList}" var="acc">
              <apex:column value="{!acc.name}" />
              <apex:column value="{!acc.AccountNumber}" />
              <apex:column value="{!acc.Type}" />
              <apex:column value="{!acc.Accountsource}" />
              <apex:column value="{!acc.Industry }" />
        </apex:pageblocktable>
     </apex:pageBlock>
   </apex:form>
</apex:page>

Apex class:
public class importDataFromCSVController {
    public Blob csvFileBody{get;set;}
    public string csvAsString{get;set;}
    public String[] csvFileLines{get;set;}
    public List<account> acclist{get;set;}
    public importDataFromCSVController(){
        csvFileLines = new String[]{};
            acclist = New List<Account>(); 
    }    
    public void importCSVFile(){
        try{
            csvAsString = csvFileBody.toString();
            csvFileLines = csvAsString.split('\n'); 
            
            for(Integer i=1;i<csvFileLines.size();i++){
                Account accObj = new Account() ;
                string[] csvRecordData = csvFileLines[i].split(',');
                accObj.name = csvRecordData[0] ;             
                accObj.accountnumber = csvRecordData[1];
                accObj.Type = csvRecordData[2];
                accObj.AccountSource = csvRecordData[3];   
                accObj.Industry = csvRecordData[4];                                                                             
                acclist.add(accObj);   
            }
            if(acclist.size()>=1 && acclist.size()<=5){
                insert acclist;
            }
            else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please upload Account records less than 5'));
                
            }
        }  catch (Exception e)
        {
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'Please upload the csv format file');
            ApexPages.addMessage(errorMessage);
        }  
    }
}

Please let me know if you have any query.
Please mark it as best Answer if you find it helpful.

Thank You
Ajay Dubedi
Sarma DuvvuriSarma Duvvuri
Hi Ajay,

Thanks for the quick response. I am getting error message  as  expected.but once i click on upload after getting the 5 records, again same records are getting fetched without uploading any file.

Please resolve.

Thanks,
Sarma
Ajay K DubediAjay K Dubedi
Hi Sarma,

1-you need to a csv file account record less than or equal to 5 to check insert record in Account Object.
2-you need to a csv file account record more than 5 to check error.
3-you can not insert duplicate record name it will throw error.
Your problem has been solved.

VisualforcePage:
<apex:page controller="importDataFromCSVController">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock >
            <apex:pageBlockSection > 
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Upload" action="{!importCSVFile}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
           <apex:pageblocktable value="{!accList}" var="acc">
              <apex:column value="{!acc.name}" />
              <apex:column value="{!acc.AccountNumber}" />
              <apex:column value="{!acc.Type}" />
              <apex:column value="{!acc.Accountsource}" />
              <apex:column value="{!acc.Industry }" />
        </apex:pageblocktable>
     </apex:pageBlock>
   </apex:form>
</apex:page>

Apex class:
public class importDataFromCSVController {
    public Blob csvFileBody{get;set;}
    public string csvAsString{get;set;}
    public String[] csvFileLines{get;set;}
    public List<account> acclist{get;set;}
    public List<String> accctNames{get;set;}
    public List<account> newAccts{get;set;}
    public boolean flag=true;
    public importDataFromCSVController(){
        csvFileLines = new String[]{};
            acclist = New List<Account>();
        newAccts = New List<Account>();
        accctNames = new List<String>();
    }  
    public void importCSVFile(){
        csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 
        if(csvFileLines.size()>=1 && csvFileLines.size()<=5){
            if(flag==true){
                for(Integer i=1;i<csvFileLines.size();i++){
                    Account accObj = new Account() ;
                    string[] csvRecordData = csvFileLines[i].split(',');
                    
                    accObj.name = csvRecordData[0] ;             
                    accObj.accountnumber = csvRecordData[1];
                    accObj.Type = csvRecordData[2];
                    accObj.AccountSource = csvRecordData[3];   
                    accObj.Industry = csvRecordData[4];  
                    accctNames.add(accObj.Name);
                    acclist.add(accObj);   
                }
                List<Account> existingAccts =new List<Account>();
                existingAccts = [SELECT Id, Name FROM Account where Name IN:accctNames];
                
                Map<String, Id> acctNamesIdMap = new Map<String, Id>();
                // load the map - this will help you find out if an account name exists already
                for (Account acct : existingAccts)
                {
                    acctNamesIdMap.put(acct.Name, acct.Id);
                    System.debug('******Sai******');
                    ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'Account ' + acct.Name + ' already exists, change Account Name and try again');
                    ApexPages.addMessage(errormsg);
                }
                
                for (Account acct : acclist)
                {
                    //if account name does not exist in map, add it to list of new accounts
                    if (!acctNamesIdMap.containsKey(acct.Name))
                    {
                        newAccts.add(acct);
                        
                    }
                }
                try
                {
                    insert newAccts;
                }
                catch (Exception e)
                {
                    ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'Account Name already exist, change Account Name and try again');
                    ApexPages.addMessage(errormsg);
                }
                flag=false;
            }
            else{
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Account Name already exist, change Account Name and try again')); 
            }
        }
        else{
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please upload Account records less than 5')); 
        }
    }
}

Please let me know if you have any query.
Please mark it as best Answer if you find it helpful.

Thank You
Ajay Dubedi
Sarma DuvvuriSarma Duvvuri
Hi Ajay,

Thanks for the quick responce. I want one clarification. Once i click on upload button i should get the pop up message to choose the file instead of choosing inputfile option in apex. Do you have any code related to that. Please me.

Sarma
Anirban Saha 8Anirban Saha 8
Hi,

It is very helpful. Could you please help on one more thing. Like if I want to insert a SFDC id value like account record type. Then how can I put it. The fields you have used are holding the string value. But what need to be done to insert a ID value.

Thanks,
Anirban