Dear awesome readers,

I have been in your shoes trying to pull my hair over wrappers! But sincerely, they ain’t that tough. What you need is patience and courage to overcome the feer of long-looking code.

Lets learn by taking the following use case then.
1. Read a CSV file with account and accountnumber fields
2. Display this data on the page along with a blank “status” column
3. Check and populate status = ‘unique’ if account isn’t already present in the database. Populate status = ‘duplicate’ if otherwise

Yes, I like shortcuts…. Lets get straight to the code now. You will find my along the code.

Controller code:

public class importDataFromCSVController_mann {

    //declare all class variables
    public Blob csvFileBody{get;set;}         //geter and setter methods for VF page access
    public string csvAsString{get;set;}

    public String[] csvFileLines;
    public string[] csvRecordData;
    public List<account> acc_lst;      //will be used to read all accounts in the org
    public Map<String,String> acc_map; //will be used to create a map from acc_lst

    //define a wrapper class that will hold account and the status!
    public class wrapAccount {
        public Account acc {get;set;}
        public String csvStatus {get;set;}

        public wrapAccount(Account a, Map<String,String> acc_map) {
            acc = a;
            if(acc_map.containsKey(a.Name)) {
                csvStatus = 'Duplicate';
            } else {
                csvStatus = 'Unique';
                //write you insert statement here (am commenting it to keep my DB clean :))
                //insert a;

            }

        }
    }

    //wrapperobject to display on VF
    public List<wrapAccount> wrapAccount_lst {get;set;}

    public List<wrapAccount> getAccounts() {
        return wrapAccount_lst;
    }

    //populate wrapperObject // **this is where the magic happens**
    public pagereference importCSVFile() {
        csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n');
        system.debug('csvFileLines= '+csvFileLines+' csvFileLines.size() = '+csvFileLines.size());

        //get all accounts
        acc_lst = new List<account>([select Name, Accountnumber from account]);
        //initialize the map
        acc_map = new Map<String,String>();
        //populate the map
        for (account a: acc_lst) {
            system.debug('a = '+a);
            acc_map.put(a.Name,a.AccountNumber);
        }

        wrapAccount_lst = new List<wrapAccount>();
        for(Integer i=0;i<csvFileLines.size();i++) { //assuming no header in the CSV
           
           //read the csv row
	    csvRecordData = csvFileLines[i].split(',');
	    //get values from csv into the account 
            Account a = new Account();
            a.name = csvRecordData[0] ;
            a.accountnumber = csvRecordData[1];
            a.Type = csvRecordData[2];
            a.AccountSource = csvRecordData[3];
            a.Industry = csvRecordData[4];
            wrapAccount_lst.add(new wrapAccount(a,acc_map)); //use constructor to assign values to the wrap and add it to our wrapper list

            //if you dont like constructors, use the following
            //            	wrapAccount wa = new wrapAccount();
            //				wa.acc = a;
            //				wa.csvStatus = <build the logic here>
            

        }
        return null; 
    }

}

Visualforce page:

<apex:page controller="importDataFromCSVController_mann">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock >
            <apex:pageBlockSection columns="4">
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Import Account" action="{!importCSVFile}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
           <apex:pageblocktable value="{!Accounts}" var="acc">
              <apex:column value="{!acc.acc.name}" />
              <apex:column value="{!acc.acc.AccountNumber}" />
              <apex:column value="{!acc.acc.Type}" />
              <apex:column value="{!acc.acc.Accountsource}" />
              <apex:column value="{!acc.acc.Industry }" />
               <apex:column headerValue="Status" >
              <apex:outputText id="status" value="{!acc.csvStatus}"/>
              </apex:column>
           </apex:pageblocktable>
        </apex:pageBlock>
   </apex:form>
</apex:page>

And that is it 🙂

Hope you enjoyed learning.
Thanks,
H Mann

Advertisements