2

i need to display text in visualforce page, what i have access to is a List. i need to display first element of this list as text on page.

List<String> listOfStrings;

<h4>{!what expression to use listOfStrings}</h4>

3 Answers 3

4

You can pass 0 at index of list as:

public List<String> listOfStrings {get;set;}
<h4>{! IF(listOfStrings.size > 0, listOfStrings[0], '') }</h4>
2
  • i cannot save page with this syntax : {!listOfStrings[0]}. Seems syntax is not valid.
    – Walker
    Commented Sep 8, 2015 at 13:46
  • 1
    Did you define get; set; ? @Walker
    – Ashwani
    Commented Sep 8, 2015 at 13:47
3

You can use regular "array" notation to show the first element. Be sure to check to make sure the list is neither null nor empty before trying to access an array element.

{!listOfStrings[0]}

Alternatively, you can use a repeat element:

<apex:repeat value="{!listOfStrings}" var="varString" rows="1">{!varString}</apex:repeat>

Obviously, this is a bit more verbose, but works all the same.

Finally, you can also simply use a getter method in Apex Code:

public String getFirstString() {
    return listOfStrings != null && listOfStrings.size() > 0? listOfStrings[0]: null;
}

Which is then used as:

{!firstString}
1

@Walker Here I have tried to create a VF page and a Controller as explained by sfdcfox and Ashwani above. Hope this helps.

VF Page

<apex:page showHeader="true" sidebar="true" controller="ListString">
    <h4>what expression to use {!listOfStrings[0]}</h4><br/>
    <h4>what expression to use <apex:repeat value="{!listOfStrings}" var="varString" rows="1">{!varString}</apex:repeat></h4><br/>
    <h4>what expression to use {!firstString}</h4><br/>
</apex:page>

Controller

public with sharing class ListString {
    public List<String> listOfStrings {get;set;}
    public ListString() {
        listOfStrings = new List<String>();
        listOfStrings.add('Hello');
        listOfStrings.add('World');
    }
    public String firstString {
        get {
            return listOfStrings != null && listOfStrings.size() > 0? listOfStrings[0]: null;
        }
        set;
    }   
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .