Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF: Adding a String to List

Tags:

list

jsf

I have an JSF 2.0 application that has a bean that holds a list of Strings.

I want to add the String from an <h:inputText>/> to my List and display my list.

The following code just put references in my List. So every element from my List is set to the last input.

@ManagedBean
@ApplicationScoped
public class Bean {

private String name;
private ArrayList<String> test = new ArrayList<String>();

public Bean() {
}

public Bean(String name) {
    this.name = name;
}


public String addtoList(String _name){
    test.add(_name);
    return "./index.xhtml";
} 


/***************GETTER/SETTER/HASHCODE/EQUALS**************************/
   ...

}

here a part of my index.xhtml:

        <h:inputText id="name"
                         value="#{bean.name}"
                         required="true">
        </h:inputText>
        <h:commandButton value="Post"  
                         action="#{bean.addtoList(name)}"/>  
        <br/>
        <h:dataTable var="bean"
                     value="#{bean.test}">
            <h:column>
                <h:outputText value="#{bean.name}"/>
            </h:column>

        </h:dataTable>

apllicationExample

like image 222
JavaNullPointer Avatar asked Apr 22 '26 21:04

JavaNullPointer


1 Answers

Try this:

public String addtoList() { // no parameter
    test.add(this.name); // add value of bean's property
    return "./index.xhtml";
}

and in the facelet:

<h:commandButton
    value="Post"
    action="#{bean.addtoList}"/> <!-- no parameter passed -->

The point is to have the addToList method without parameters and the string you add to the list should be the value of the name property of the backing bean.

And also, in the datatable, do not name the var the same as the backing bean. It's confusing and potentially leads to bugs. Use something like this:

<h:dataTable
    var="it"
    value="#{bean.test}">
    <h:column>
        <h:outputText value="#{it}" />
    </h:column>
</h:dataTable>
like image 71
Natix Avatar answered Apr 24 '26 16:04

Natix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!