actionstatus visualforce disable screen

actionstatus visualforce disable screen

actionStatus visualforce component displays the status of an AJAX update request. An AJAX request can either be in progress or complete.

Depending upon the AJAX request status (whether AJAX request is in progress or complete), this component will display different message to user. In many scenarios AJAX request takes some time. So we should display some message to user that your request is in progress. Once request is complete, we can display some different message to user.

Using actionstatus, we can also display some gif (graphic Interchange Format), which shows to user that their request is in progress. It gives very good presentation to end user.

In the example below, we are using actionStatus for commandbutton. We are showing account edit page to user. When user will click on save buttton, request will go to controller method. We are showing gif image to user while AJAX request is in progress using actionstatus component. We are using apex:facet tag inside actionstatus to show image and we have specified name value as ‘start’ in apex:facet tag. So It will show image when request is in progress. We can also use ‘stop’ value in name attribute of apex:facet to specify message when request completes.

Click for Demo

actionstatus visualforce disable screen

Visualforce Page:

<apex:page controller="actionStatusImage" tabStyle="Account">
    <apex:outputpanel >
        <apex:actionstatus id="actStatusId">
            <apex:facet name="start">
                <div class="waitingSearchDiv" id="el_loading" style="background-color: #DCD6D6;
                       height: 100%;opacity:0.65;width:100%;"> 
                    <div class="waitingHolder" style="top: 74.2px; width: 91px;">
                        <img class="waitingImage" src="/img/loading.gif" title="Please Wait..." />
                        <span class="waitingDescription">Saving...</span>
                    </div>
                </div>
            </apex:facet>
        </apex:actionstatus>
    </apex:outputpanel>
    <apex:form id="formId">
    <apex:pageBlock id="pgBlckId" title="New Account">
        
        <apex:pageBlockButtons >
            <apex:commandButton action="{!save}" value="Save" reRender="pgBlckId" status="actStatusId"/>
        </apex:pageBlockButtons>
        
        <apex:pageBlockSection id="pgBlckSecId" title="Account Information" collapsible="false">
            <apex:inputField value="{!account.name}"/>
            <apex:inputField value="{!account.Phone}"/>
            <apex:inputField value="{!account.Type}"/>
            <apex:inputField value="{!account.Rating}"/>
            <apex:inputField value="{!account.Industry}"/>
            <apex:inputField value="{!account.site}"/>
        </apex:pageBlockSection>
    </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Code:

public class actionStatusImage {
    public Account account{get;set;}
    public actionStatusImage(){
        account = new Account();
    }
    public Pagereference save(){
        //upsert account;
        return null;
    }
}

Permanent link to this article: https://www.sfdcpoint.com/salesforce/actionstatus-visualforce-disable-screen/

custom label in apex code salesforce

custom label in apex code salesforce example

We can use System.Label.labelName to access custom label in apex code.

Custom labels are custom text values that can be accessed from Apex classes or Visualforce pages. The values can be translated into any language Salesforce supports. Custom labels enable developers to create multilingual applications by automatically presenting information (for example, help text or error messages) in a user’s native language.
You can create up to 5,000 custom labels for your organization, and they can be up to 1,000 characters in length.

To access custom labels, Go To Setup — Create — Custom Labels. Click on New Custom Labels.Enter value for name, value and description. We can use custom label name to access custom label value in apex code using System.Label.labelName

New Custom Label

Advantage of using custom label is that label will be displayed to user depending on their language automatically. We need to specify translation for label using translation workbench.

After creating custom label we can use following code to use custom label in apex code.

Visualforce Page:

<apex:page controller="CustomLabelApexDemoController">
   <apex:form >
     <apex:pageblock >
       Value stored in custom label is: <b>{!customLabelValue}</b>
     </apex:pageblock>
   </apex:form>
</apex:page>
public class CustomLabelApexDemoController {
    public string customLabelValue{get;set;}
    public CustomLabelApexDemoController(){
        customLabelValue = System.Label.DemoLabel;
    }
}

If custom label is part of managed package, then we also need to use namespace for accessing custom label in our custom apex code which is not part of managed package. Lets say DemoLabel is part of managed package and managed package namespace is ‘myName’. Then we need to use following code to access DemoLabel in apex code.

String customLabelValue = System.Label.myName.DemoLabel;

We can also use custom label in visualforce page. For more details check this post.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/custom-label-in-apex-code-salesforce/

custom label in visualforce page

custom label in visualforce page salesforce

We can use $Label global variable to access custom label in visualforce page.

Custom labels are custom text values that can be accessed from Apex classes or Visualforce pages. The values can be translated into any language Salesforce supports. Custom labels enable developers to create multilingual applications by automatically presenting information (for example, help text or error messages) in a user’s native language.
You can create up to 5,000 custom labels for your organization, and they can be up to 1,000 characters in length.

To access custom labels, Go To Setup — Create — Custom Labels. Click on New Custom Labels.Enter value for name, value and description. We can use custom label name to access custom label value in visualforce page using $Label global variable.

New Custom Label

Advantage of using custom label is that label will be displayed to user depending on their language automatically. We need to specify translation for label using translation workbench.

After creating custom label we can use following code to use custom label in visualforce page

Click for Demo

Visualforce Page:

<apex:page tabStyle="Account">
   <apex:form >
     <apex:pageblock >
       <apex:outputText value="Value stored in Demo custom label is : "/>
       <apex:outputText value="{!$Label.DemoLabel}" style="font-weight:bold"/>
     </apex:pageblock>
   </apex:form>
</apex:page>

If custom label is part of managed package, then we also need to use namespace for accessing custom label in our custom visualforce page which is not part of managed package. Lets say DemoLabel is part of managed package and managed package namespace is ‘myName’. Then we need to use following code to access DemoLabel in Visualforce page.

<apex:outputText value="{!$Label.myName__DemoLabel}" style="font-weight:bold"/>

We can also use custom label in apex code. For more details check this post

Permanent link to this article: https://www.sfdcpoint.com/salesforce/custom-label-in-visualforce-page/

Trigger on Attachment in Salesforce

Trigger on Attachment in Salesforce

Many times I have seen question from others that how can we write trigger on attachment in salesforce. For the Attachment, ContentDocument and Note standard objects, we can’t create a trigger in the Salesforce user interface. For these objects, we can create a trigger using development tools, such as the Developer Console or the Force.com IDE. Alternatively, we can also use the Metadata API.

In this example we will learn to write trigger on attachment object in salesforce. Firstly I will explain using developer console. Here are steps to create trigger on attachment using developer console.

1. Click on your name at (top left corner) and Select “Developer Console”

developer console

2. Go to File -> New -> Apex Trigger.

Debeloper Console 2

3. Select name of SObject and enter name of trigger

developer console3

4. Click on submit button. In this way we can create trigger on attachment.

In similar way we can also create trigger using force.com IDE.

We should be very careful while writing the trigger on Attachment, as it will be used by all standard or custom Object on which attachment is added. We should provide criteria to run trigger so that trigger should be executed for required objects only.

In this example I will create the trigger which will check for the parent object “Account”. If the object is Account then it will update one field on account record.

Trigger Code:

trigger AttachmentTriggerDemo on Attachment (before insert) {
    List accountList = new List();
    Set accIds = new Set();
    for(Attachment att : trigger.New){
         //Check if added attachment is related to Account or not
         if(att.ParentId.getSobjectType() == Account.SobjectType){
              accIds.add(att.ParentId);
         }
    }
    accountList = [select id, has_Attachment__c from Account where id in : accIds];
    if(accountList!=null && accountList.size()>0){
        for(Account acc : accountList){
            acc.has_Attachment__c = true;
        }
        update accountList;
    }
}

Permanent link to this article: https://www.sfdcpoint.com/salesforce/trigger-on-attachment-in-salesforce/

SOSL Example in Salesforce

SOSL Example in Salesforce

SOSL Example in Salesforce

What is SOSL in Salesforce?

Salesforce Object Search Language (SOSL) is a Salesforce search language that is used to perform text searches in records. Use SOSL to search fields across multiple standard and custom object records in Salesforce.  SOSL is a search language in salesforce and the important feature is that Unlike SOQL, we can search in multiple objects at same time using SOSL. In SOQL, we can query only one object at a time but in SOSL, We can search for some specified string like ‘testString’ in multiple objects at the same time.

  • We can search for some specified string like ‘testString’ in multiple objects at the same time.
  • We can mention in which fields of all the sObjects,we want to search for the string specified.
  • The SOSL query start with the keyword ‘FIND’.
  • You can specify, which fields to return for each object mentioned in SOSL query. Suppose you have performed search on three objects Account, Contact & Opportunity. Then you can mention like, for list returned with Account results only (Name, Industry) fields should come, and for Contacts results (firstName, lastName) should come and similarly for Opportunity.
  • The result of SOSL is a list of lists of sObjects “List<List<sObject>>”.
  • The returned result contains the list of sObjects in the same order as order mentioned in SOSL  query.
  • If a SOSL query does not return any records for a specified sObject type, then search results include an empty list for that sObject.
  • The search string should be at least two characters long.

Here is the quick demo SOSL Demo

SOSL-Example-in-Salesforce

Below is the sample code that has a input text box and a command button which will search for the entered string in three Object . i.e Accounts, Contacts, Opportunities and returned result will be shown in the page block tables.

SOSL Visualforce page

<apex:page controller="SOSLController">
  <apex:form >
  <apex:inputText value="{!searchStr}"/>
    <apex:commandButton value="Search in Account, Contact, Opportunity" action="{!soslDemo_method}"                reRender="acct,error,oppt,cont" status="actStatusId"/>
    <apex:actionStatus id="actStatusId">
                <apex:facet name="start" >
                    <img src="/img/loading.gif"/>                    
                </apex:facet>
    </apex:actionStatus>
  </apex:form>
 
    <apex:outputPanel title="" id="error">
     <apex:pageMessages ></apex:pageMessages>
     </apex:outputPanel>
 
    <apex:pageBlock title="Accounts" id="acct">
    <apex:pageblockTable value="{!accList }" var="acc">
          <apex:column value="{!acc.name}"/>
          <apex:column value="{!acc.Type}"/>
       </apex:pageblockTable>
    </apex:pageBlock>
 
 <apex:pageBlock title="Contacts" id="cont">
    <apex:pageblockTable value="{!conList}" var="con">
      <apex:column value="{!con.name}"/>
      <apex:column value="{!con.email}"/>
 </apex:pageblockTable>
 </apex:pageBlock>
  
 <apex:pageBlock title="Opportunities" id="oppt">
    <apex:pageblockTable value="{!optyList}" var="opty">
      <apex:column value="{!opty.name}"/>
     <apex:column value="{!opty.StageName}"/>
 </apex:pageblockTable>
 </apex:pageBlock>
   
</apex:page>

SOSL Apex Controller

Public with sharing class SOSLController{
 Public List<Opportunity> optyList {get;set;}
 Public List<contact> conList{get;set;}
 Public List<account> accList{get;set;}
  
 Public String searchStr{get;set;}
   Public SOSLController(){
   }
  
  Public void soslDemo_method(){
   optyList = New List<Opportunity>();
   conList = New List<contact>();
   accList = New List<account>();
   if(searchStr.length() > 1){
   String searchStr1 = '*'+searchStr+'*';
   String searchQuery = 'FIND \'' + searchStr1 + '\' IN ALL FIELDS RETURNING  Account (Id,Name,type),Contact(name,email),Opportunity(name,StageName)';
   List<List <sObject>> searchList = search.query(searchQuery);
   accList = ((List<Account>)searchList[0]);
   conList  = ((List<contact>)searchList[1]);
   optyList = ((List<Opportunity>)searchList[2]);
   if(accList.size() == 0 && conList.size() == 0 && optyList.size() == 0){
       apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Sory, no results returned with matching string..'));
       return;
   }
   }
   else{
   apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Please enter at least two characters..'));
   return;
   }
  }
}

Difference between SOQL and SOSL

Like SOQL, SOSL allows you to search your organization’s records for specific information. Unlike SOQL, which can only query one standard or custom object at a time, a single SOSL query can search all objects.

Another difference is that SOSL matches fields based on a word match while SOQL performs an exact match by default (when not using wildcards). For example, searching for ‘Digital’ in SOSL returns records whose field values are ‘Digital’ or ‘The Digital Company’, but SOQL returns only records with field values of ‘Digital’.

SOQL and SOSL are two separate languages with different syntax. Each language has a distinct use case:

  • Use SOQL to retrieve records for a single object.
  • Use SOSL to search fields across multiple objects. SOSL queries can search most text fields on an object.

For more information and possibilities in SOSL, please refer trailhead

Permanent link to this article: https://www.sfdcpoint.com/salesforce/sosl-example-in-salesforce/

SOQL query in javascript example

SOQL query in javascript example

You can use SOQL in java-script on your VF pages or any kind of java-script that you write, like we can get it executed on click of a button or link present on your detail page of a record. Below is the simple example and you can use it and modify it accordingly :

Javascript code:

{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")}
try{
var query = "SELECT Id,Name from Account LIMIT 2";
var records = sforce.connection.query(query);
var records1 = records.getArray('records');
alert(records);
var accountNames = '';
for(var i=0;i<records1.length;i++){
accountNames = accountNames + records1[i].Name + ',';
}
alert(accountNames);
if(records1.length == 1){
//window.location.href = 'http://www.google.com';
}
else{
alert('There is no Account');
}
}
catch(e){
alert('An Error has Occured. Error:' +e);
}

you need to use .js files that are in first two lines in order to use the api of salesforce to connect and fetch the records using SOQL. In the example you will see result of SOQL in alert statement. The result that is returned contains a ‘records’ named array component that can be used to iterate over and go through all the records and use it in the same manner as we do in usual apex program. For ex account.id, account.Name etc.

You can also use merge fields to create dynamic queries.

Similarly you can use javascript to create, update or delete the salesforce object’s records using API. Below is the sample code you can use to create a new account record in your org.

Javascript code:

try{
var accounts = [];
var account = new sforce.SObject("Account");
account.Name = "my new account Test";
accounts.push(account);
var results = sforce.connection.create(accounts);
if (results[0].getBoolean("success")) {
alert("new account created with id " + results[0].id);
} else {
alert("failed to create account " + results[0]);
}
}
catch(e){
alert('An Error has Occured. Error:' +e);
}

you just need to create a new button and fill the details as shown below in the screenshot:

SOQL in javascript example

Below this there would be a text box where you need to write your javascript code (provided above). After saving the button, you need to get it on your page layout and we are good to go.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/soql-query-in-javascript-example/

Custom Visualforce Component example

Custom Visualforce Component example

Custom visualforce components are very useful. In our projects, many times we develop codes which are required again and again. So instead of repeating same code again and again, we can create visualforce component. Then we can use visualforce component in every place where we need that particular piece of code. In other words, custom visualforce component allows us to create reusable component.

All custom visualforce component definitions must be wrapped inside a single <apex:component > tag.

We can also use <apex:attribute> tag to use customize the component so that custom component can be used in different manners depending on value of different attributes. It helps us in creating reusable generic component and also saves time and number of lines we write in apex and visualforce page.

In the example below, we will learn to create very basic custom visualforce component.

Click for Demo

Custom Visualforce Component example

First we will create visualforce component. Go to Setup -> Develop -> Components -> then write component name. In our case component name is ‘myComponent’.

Component Code:

<apex:component >
    <apex:attribute name="textValue" description="This is the value for the component" type="String" required="true"/>
    <apex:attribute name="textColor" description="This is color for the border." type="String" required="true"/>
    <apex:outputText value="{!textValue}" style="color:{!textColor};"/>
</apex:component>

This component is creating two attributes using <apex:attribute> tag. First attribute is deciding what text text should be displayed and second attribute is deciding color of text. We can use any number of attribute in component. Component can also have controller which helps in more customizable component.

Now we need to use this component. We can use component in visualforce page using <c:componentName>.

Visualforce Code:

<apex:page tabStyle="Account"> 
    <apex:pageBlock >
        <apex:pageBlockSection title="myComponent Test" collapsible="false">
            <c:myComponent textValue="This Text is blue" textColor="blue" />
            <c:myComponent textValue="But this is red" textColor="red" />
        </apex:pageBlockSection>
    </apex:pageBlock>     
</apex:page>

Permanent link to this article: https://www.sfdcpoint.com/salesforce/custom-visualforce-component-example/

actionstatus visualforce loading image

actionstatus visualforce loading image

apex:actionStatus visualforce loading image

actionStatus visualforce component displays the status of an AJAX update request. An AJAX request can either be in progress or complete. It can be done using apex:actionStatus

Depending upon the AJAX request status (whether AJAX request is in progress or complete), this component will display different message to user. In many scenarios AJAX request takes some time. So we should display some message to user that your request is in progress. Once request is complete, we can display some different message to user.

Using actionstatus, we can also display some gif (graphic Interchange Format), which shows to user that their request is in progress. It gives very good presentation to end user.

In the example below, we are using actionStatus for commandbutton. We are showing account edit page to user. When user will click on save buttton, request will go to controller method. We are showing gif image to user while AJAX request is in progress using actionstatus component. We are using apex:facet tag inside actionstatus to show image and we have specified name value as ‘start’ in apex:facet tag. So It will show image when request is in progress. We can also use ‘stop’ value in name attribute of apex:facet to specify message when request completes.

Click for Demo

actionstatus visualforce loading image

Visualforce Page:

<apex:page controller="actionStatusImage" tabStyle="Account">
    <apex:form id="formId">
    <apex:pageBlock id="pgBlckId" title="New Account">
        
        <apex:pageBlockButtons >
            <apex:commandButton action="{!save}" value="Save" reRender="pgBlckId" status="actStatusId"/>
            <apex:actionStatus id="actStatusId" >
                <apex:facet name="start" >
                  <img src="/img/loading.gif" />                    
                </apex:facet>
            </apex:actionStatus>
        </apex:pageBlockButtons>
        
        <apex:pageBlockSection id="pgBlckSecId" title="Account Information" collapsible="false">
            <apex:inputField value="{!account.name}"/>
            <apex:inputField value="{!account.Phone}"/>
            <apex:inputField value="{!account.Type}"/>
            <apex:inputField value="{!account.Rating}"/>
            <apex:inputField value="{!account.Industry}"/>
            <apex:inputField value="{!account.site}"/>
        </apex:pageBlockSection>
    </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Code:

public class actionStatusImage {
    public Account account{get;set;}
    public actionStatusImage(){
        account = new Account();
    }
    public Pagereference save(){
        //upsert account;
        return null;
    }
}

Permanent link to this article: https://www.sfdcpoint.com/salesforce/actionstatus-visualforce-loading-image/

Custom Picklist in visualforce salesforce

Custom Picklist in visualforce salesforce

Sometime there is requirement to display custom picklist field in visualforce page. If we have a picklist field then it can be displayed using inputfield tag easily. But if we want to display a custom values in picklist, It can not be done using inputfield tag. We can display custom picklist using ‘selectList’ tag in visualforce. We can display values or options for custom picklist using ‘selectOption’ or ‘selectOptions’ tag.

In the example below, we are showing two custom picklist. In first picklist we are using selectList with selectOption. We are showing list of countries using selectOption. In second picklist we are using selectList with selectOptions to display list of countries. We are setting selectOption list using apex code. We are setting list manually in Apex code, we can also set list dynamically using SOQL query and apex code in controller. In the example below, select value in both picklist and then click on save button. Then, selected picklist value will be shown in page.

Click for Demo

Custom Picklist in Visualforce Salesforce

 

Visualforce Page:

<apex:page controller="customPickListInVFDemoController" tabStyle="Account">
  <apex:form >
    <apex:pageBlock title="Custom PickList Demo" id="out">
        <apex:pageBlockButtons >
            <apex:commandButton value="Save" action="{!save}" rerender="out" status="actStatusId"/>
            <apex:actionStatus id="actStatusId">
                <apex:facet name="start">
                    <img src="/img/loading.gif" />
                </apex:facet>
            </apex:actionStatus>
        </apex:pageBlockButtons>
        <apex:pageBlockSection title="Custom Picklist Using selectList and selectOption" collapsible="false">
            <apex:selectList value="{!selectedCountry1}" multiselect="false" size="1">
                <apex:selectOption itemValue="INDIA" itemLabel="India"/>
                <apex:selectOption itemValue="USA" itemLabel="USA"/>
                <apex:selectOption itemValue="United Kingdom" itemLabel="UK"/>
            </apex:selectList>
            
            <apex:outputText value="{!selectedCountry1}" label="You have selected:"/>
        </apex:pageBlockSection>
        
        <apex:pageBlockSection title="Custom Picklist Using selectList and selectOptions" collapsible="false">
            <apex:selectList value="{!selectedCountry2}" multiselect="false" size="1">
                <apex:selectOptions value="{!countriesOptions}"/>
            </apex:selectList>
            
            <apex:outputText value="{!selectedCountry2}" label="You have selected:"/>
        </apex:pageBlockSection>
    </apex:pageblock>
  </apex:form>
</apex:page>

Apex Code:

public class customPickListInVFDemoController {
public String selectedCountry1{get;set;}
public String selectedCountry2{get;set;}
    public customPickListInVFDemoController(){
    }
    
    public List<SelectOption> getCountriesOptions() {
        List<SelectOption> countryOptions = new List<SelectOption>();
        countryOptions.add(new SelectOption('','-None-'));
        countryOptions.add(new SelectOption('INDIA','India'));
        countryOptions.add(new SelectOption('USA','USA'));
        countryOptions.add(new SelectOption('United Kingdom','UK'));
        countryOptions.add(new SelectOption('Germany','Germany'));
        countryOptions.add(new SelectOption('Ireland','Ireland'));

        return countryOptions;
    }
    public PageReference save(){
        return null;
    }
}

Permanent link to this article: https://www.sfdcpoint.com/salesforce/custom-picklist-in-visualforce-salesforce/

Import csv file using apex visualforce

Import csv file using apex visualforce

Normally we use Apex data loader to import data in salesforce from CSV file. Now a days some other tools are also available to load data in salesforce like Jitterbit data loader. But sometime there is requirement when end users do not want to use Apex Data loader. They want some custom page to load data in salesforce. Then in that case we can use custom code to load data in salesforce from csv file.

Also sometime using single CSV file we want to load data in multiple objects. Then in that case we can not use data loader to load data. In that case we can use custom code to load data in salesforce.

In the example below we are loading data from CSV file for account objects.

First of all we need CSV file format. Click here to download CSV file. You can modify CSV file to insert or import account records. CSV file attached has following format:

Import csv file using apex visualforce

Now we need to write code in Apex and visualforce which will  read csv file and insert records in account object.

Click on choose file, then select csv file and then click on ‘Import Account’ button. All records from csv file will be inserted on account records. I have commented insert account line. So this example will only show account records on visualforce page. You can uncomment insert account list line in below code if you want to insert account list.

Click for demo

Import csv file using apex visualforce

Visualforce Page:

<apex:page controller="importDataFromCSVController">
    <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="{!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 Code:

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,'An error has occured while importin data Please make sure input csv file is correct');
            ApexPages.addMessage(errorMessage);
        }  
  }
}

Permanent link to this article: https://www.sfdcpoint.com/salesforce/import-csv-file-using-apex-visualforce/