Friday, May 13, 2022

Subscript is invalid because list is empty | Error in VF Page | Salesforce

Subscript is invalid because list is empty this error is comes on VF page if we are trying to access the list element on VF Page and in the apex the list has no rows.

Below is the example 

Here is my Apex Class

public Class myClass {

    public Account account {get;set;} 

public myClass(){

        recordId = System.currentPageReference().getParameters().get('recordId');

        this.account = [SELECT Id, Name,(select id,LastName FROM Contacts) FROM Account WHERE Id =:recordId];                

    }

}


VF Page

<apex:page renderAs="pdf" applyBodyTag="false" controller="myClass" >

<div class="header">

        <table>         

            <tr>

                <td style="background: #D6EEEE"><b>Account Name</b></td>   

                <td>{!account.Name}</td> 

                <td style="background: #D6EEEE"><b>Contact Last Name</b></td>  

                <td>{!account.Contacts[0].LastName}</td> 

        </tr>

    </table>



In order to solve this error we'll have to modify our code as below

public Class myClass {

    public Account account {get;set;} 

    public String contactLastName {get;set;}

public myClass(){

        recordId = System.currentPageReference().getParameters().get('recordId');

        contactLastName = '';

        this.account = [SELECT Id, Name,(select id,LastName FROM Contacts) FROM Account WHERE Id =:recordId];           

    if(this.account.contacts.size() >0){

        contactLastName = this.account.contacts[0].LastName;

    }     

    }

}


VF Page

<apex:page renderAs="pdf" applyBodyTag="false" controller="myClass" >

<div class="header">

        <table>         

            <tr>

                <td style="background: #D6EEEE"><b>Account Name</b></td>   

                <td>{!account.Name}</td> 

                <td style="background: #D6EEEE"><b>Contact Last Name</b></td>  

                <td><!--{!account.Contacts[0].Name}-->{!contactLastName}</td> 

        </tr>

    </table>


Hope this will solve your problem, Please comment below if you have any question. I'll be happy to help.

No comments:

Post a Comment