The autocomplete method successfully shows the String List of userNames but not adding it to the selected users. I tried and search a lot please help me any one.
xhtml file
...
...
<div class="ui-sm-12 ui-md-2 ui-lg-2">
<p:outputLabel value="Users" />
</div>
<div class="ui-sm-12 ui-md-4 ui-lg-4">
<h:inputHidden value="#{service.usersListSize}" id="iTUsers" />
<p:autoComplete id="usersid" widgetVar="userswVar" maxlength="60" minQueryLength="1"
maxResults="10" styleClass="actCont" style="width: 100%;height:50px;"
value="#{service.users}"
completeMethod="#{service.completeUserName}" var="u" unique="true"
itemLabel="#{u}" itemValue="#{u}" multiple="true" forceSelection="true" disabled="#{service.disableFields}">
<p:ajax event="itemSelect" listener="#{service.getListValues()}" update="jbForm:tabview:iTUsers"/>
</p:autoComplete>
</div>
...
...
Service.java file
....
....
private int usersListSize;
private List<String> users = new ArrayList<>();
public int getUsersListSize() {
return usersListSize;
}
public void setUsersListSize(int usersListSize) {
this.usersListSize = usersListSize;
}
public List<String> getUsers() {
return users;
}
public void setUsers(List<String> users) {
this.users = users;
}
public List<String> completeUerName(String query) {
if (!query.startsWith("#")) {
return new ArrayList<>();
}
String queryLowerCase = query.toLowerCase();
List<String> uName = getListOfUsersName();
return uName.stream().filter(t -> t.toLowerCase().contains(queryLowerCase)).collect(Collectors.toList());
}
public List<String> getListOfUsersName() {
List<String> usersNamesList;
usersNamesList.add("jhon");
usersNamesList.add("jhonny");
usersNamesList.add("Richard D'souza");
usersNamesList.add("sheri'f");
usersNamesList.add("ja'mes");
List<String> userNameList = new ArrayList<>();
for (String u : usersNamesList) {
userNameList.add("#" + u);
}
return userNameList.stream().filter(t -> t.toLowerCase().contains("#")).collect(Collectors.toList());
}
public void getListValues() {
setUsersListSize(this.users.size());
}
public void listUsers(Integer id) {
users = retrieveUsersLst(id);
}
public List<String> retrieveUsersLst(Integer id) {
List<String> ppList = new ArrayList<>();
List<Users> userList = usersList(id);
if (userList != null && !userList .isEmpty()) {
int listSize = userList .size();
String userName;
for (int i = 0; i < listSize; i++) {
userName = "#" + getUserName(userList .get(i).getId());
ppList.add(userName);
}
}
return ppList;
}
public List<Users> usersList(Integer id) {
String queryString = "from Users where id=" + id;
return dao.qryList(queryString, Dao.query.HQL);
}
public String getUserName(Integer uId) {
String queryString = "select userName from Users where id=" + uId;
return (String) dao.qryUniqueResult(queryString, Dao.query.HQL);
}
It works fine except if user name contains any quotes Like this ' then the value is not selecting. I don't know why.
please help me to resolve this issue. Thanks in advance.
using prime faces 6.2.
The problem is how the unique attribute of autocomplete is managed in PF 6.2.
As you can see, from any browser developer tools, clicking on an item that contains the ' character, will generate an error, like this:
Uncaught Error: Syntax error, unrecognized expression: li[data-token-value='#Richard D'souza']
The error, in the components.js is:
PrimeFaces.widget.AutoComplete
...
h = PrimeFaces.escapeHTML(e.replace(/\"/g, '\''));
...
if (a.cfg.multiple) {
var j = false;
if (a.cfg.unique) {
j = a.multiItemContainer.children('li[data-token-value=\'' + h + '\']').length != 0
}
Note that if you type the entire string, there's no error and the item is added.
This is already resolved in the newer PF version with:
PrimeFaces.widget.AutoComplete
...
var i = f.attr("data-item-value");
...
if (a.cfg.multiple) {
var h = false;
if (a.cfg.unique) {
h = a.multiItemContainer.children("li[data-token-value='" + $.escapeSelector(i) + "']").length != 0
}
As a solution you could:
Upgrade PF, >= 7.0
Remove the unique attribute, if your use case doesn't need it, or manage it at selection event (server-side)
Override that function, in PF 6.2 adding escape logic
Related
I am writing a filter to filter person names which are displayed in a column pertaining to a vaadin grid. I add a data provider with row objects as follows:
ListDataProvider<Row> dataProvider = new ListDataProvider<>(dataSet.getRows());
Grid.Column<Row, Object> colName = grid.addColumn(row -> row.getValue("NAME")).setCaption("NAME");
grid.setDataProvider(dataProvider);
HeaderRow filterRow = grid.appendHeaderRow();
RowFilter filterObject = new RowFilter();
dataProvider.setFilter(row -> filterObject.test(row, "NAME"));
TextField nameField = new TextField();
nameField.addValueChangeListener(event -> {
filterObject.setName(event.getValue());
dataProvider.refreshAll();
});
nameField.setValueChangeMode(ValueChangeMode.EAGER);
filterRow.getCell(colName).setComponent(nameField);
nameField.setSizeFull();
nameField.setPlaceholder("Filter");
nameField.getElement().setAttribute("focus-target", "");
The row filter looks as follows:
package com.example.vaadin.utils;
import org.apache.commons.lang3.StringUtils;
public class RowFilter {
String name = "";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean test(com.example.vaadin.views.ContactView.Row row, String columnval) {
if (name.length() > 0 && !StringUtils
.containsIgnoreCase(String.valueOf(row.getValue(columnval)),
name)) {
return false;
}
return true;
}
}
Here is my row class:
package com.example.vaadin.utils;
import org.apache.commons.lang3.StringUtils;
public class RowFilter {
String name = "";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean test(com.example.vaadin.views.ContactView.Row row, String columnval) {
if (name.length() > 0 && !StringUtils
.containsIgnoreCase(String.valueOf(row.getValue(columnval)),
name)) {
return false;
}
return true;
}
}
The problem is the following one:
When I want to add the attribute focus-target to the nameField like this - nameField.getElement().setAttribute("focus-target", ""); - but com.vaadin.ui.TextField does not seem to have a getElement method in vaadin 8. I have been looking for a workaround to get this problem fixed, but to no avail. This is why I’d like to ask here whether anybody can tell me if there is one.
getElement() was added in Vaadin 10 and is not included in Vaadin 8. There is no built-in way of setting arbitrary attributes in Vaadin 8, so you would instead have to take to low-level solutions such as building a simple client-side extension or using Javascript::execute.
I have a blazor component:
#inject IJSRuntime JSRuntime
#using bullDocDBAcess
#using bullDocDBAcess.Models
#inject ITagData _db
#if(tags == null){
<p><em>Loading...</em></p>
}else{
<input type="text" #bind=#tags data-role="tagsinput" />
<input type="hidden" #onchange="onChange" value=#tags />
}
#code{
private string tags = "";
private List<TagModel> tagsList;
private Task<IJSObjectReference> _module;
private Task<IJSObjectReference> Module => _module ??= JSRuntime.InvokeAsync<IJSObjectReference>("import", "./components/tagsinput/tags_inputs_imports.js").AsTask();
[Parameter]
public int organizationId { get; set; } = 0;
[Parameter]
public int documentId { get; set; } = 0;
[Parameter] public EventCallback<Notification> OnTagsChange { get; set; }
private void onChange(Microsoft.AspNetCore.Components.ChangeEventArgs args)
{
tags = (string) args.Value;
OnTagsChange.InvokeAsync(new Notification(tags, documentId.ToString()));
}
protected override async Task OnInitializedAsync()
{
if(organizationId == 0){ //inserção
tags = "";
}else{
tagsList = await _db.GetTagsFromDocument(organizationId, documentId);
foreach (TagModel t in tagsList){
if(String.IsNullOrEmpty(tags)){
tags += t.nome;
}else{
tags += "," + t.nome;
}
}
}
var module = await Module;
await module.InvokeVoidAsync("loadScripts");
}
public async ValueTask DisposeAsync()
{
if (_module != null)
{
var module = await _module;
await module.DisposeAsync();
}
}
}
Basically, the idea is to use a bootstrap input tag (called using jsinterop) and include it several times for each product in a table. When tags and updated in this table, the database should be updates with the tags for that specific values.
The parent component:
(...)
#for(int i=0;i<this.document.Count;i++)
{
DocumentModel p = this.document.ElementAt(i);
<tr>
<td><TagManagement #key=#p.id organizationId=#p.organizacao_id documentId=#p.id OnTagsChange="TagsHandler" /></td>
</tr>
}
(...)
void TagsHandler(Notification notification)
{
Console.WriteLine("Hello"); //only for testing purposes
}
A two-way binding is implemented between the parent and child. However, o have no idea how to handle multiple component invocation with callback function for each one. When a new tag is inserted, only works on the first element of the table and the event is fired two times (because in this test I only have two rows).
I tried to include the key attribute but didn't work. Can you please help me?
Best regards
Ok so i have a data table that is supposed to be an admin page for a book store. I have got everything working on it except i am supposed to have a check box on each row that will switch the outputs to inputs and let you edit a book in the table
i have confirmed through the console that it is running the method and setting the boolean value to true, but it is not re rendering the row to be editable. Any help would be greatly appreciated. I am still very new to JSF
My index page
<h:body>
<h:form>
<h1>Administrator Page</h1>
<br></br>
<br></br>
<h:dataTable value="#{bookDatabase.books}"
rowClasses="evenRow,oddRow"
id="edit"
var="book">
<h:column>
<f:facet name="header">edit</f:facet>
<h:selectBooleanCheckbox value="#{book.editable}"
onclick="submit()"/>
</h:column>
<h:column>
<f:facet name="header">Title</f:facet>
<h:inputText value="#{book.title}"
rendered="#{book.editable}" size="10"/>
<h:outputText value="#{book.title}"
rendered="#{not book.editable}"/>
</h:column>
<h:column>
<f:facet name="header">Author</f:facet>
<h:inputText value="#{book.author}"
rendered="#{book.editable}" size="10"/>
<h:outputText value="#{book.author}"
rendered="#{not book.editable}"/>
</h:column>
<h:column>
<f:facet name="header">Price</f:facet>
<h:outputText id="unitPrice2" value="#{book.price}"
rendered="#{not book.editable}">
<f:convertNumber currencyCode="USD" type="currency" />
</h:outputText>
<h:inputText id="unitPrice" value="#{book.price}"
rendered="#{book.editable}" size="10">
<f:convertNumber currencyCode="USD" type="currency" />
</h:inputText>
</h:column>
<h:column>
<h:commandLink value="Delete"
action="#{bookDatabase.removeBook(book.title)}"/>
</h:column>
</h:dataTable>
<br></br>
Title: <h:inputText id="title" value="#{bookDatabase.title}"/> <br></br>
Author: <h:inputText id="author" value="#{bookDatabase.author}"/> <br></br>
Price: <h:inputText id="price" value="#{bookDatabase.price}"/> <br></br>
<h:commandButton id="submit" value="Submit" action="#{bookDatabase.addBook()}"/>
<br></br>
</h:form>
</h:body>
The book class
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
public class Book implements Serializable {
String title;
String author;
double price;
String orderNumeber;
int quan;
double sub;
double total;
boolean editable;
public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
Book() {
title = null;
author = null;
price = 0.0;
orderNumeber = "";
quan = 0;
sub = 0.0;
total = 0.0;
editable = false;
}
public String editableCheck(String title) {
System.out.print(title);
if (this.title.equals(title)) {
if (editable == true) {
editable = false;
} else {
editable = true;
}
}
System.out.print(editable);
return null;
}
public boolean isEditable() {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public int getQuan() {
return quan;
}
public void setQuan(int quan) {
this.quan = quan;
}
public double getSub() {
return sub;
}
public void setSub(double sub) {
this.sub = sub;
}
public String getOrderNumeber() {
return orderNumeber;
}
public void setOrderNumeber(String orderNumeber) {
this.orderNumeber = orderNumeber;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
I dont think my bookDatabase class has any affect on it but here it is just in case
#Named(value = "bookDatabase")
#SessionScoped
public class BookDatabase implements Serializable {
/**
* Creates a new instance of BookDatabase
*/
private List<Book> books;
#Resource(name = "jdbc/database2")
private DataSource ds;
private boolean display;
private boolean edit;
private boolean add;
private boolean remove;
private String title;
private String author;
private String price;
private String bookToRemove;
Book addBook;
#PostConstruct
public void init() {
books = new ArrayList<>();
display = false;
edit = false;
add = false;
remove = false;
addBook = new Book();
title = null;
author = null;
price = null;
bookToRemove= null;
}
public String getBookToRemove() {
return bookToRemove;
}
public void setBookToRemove(String bookToRemove) {
this.bookToRemove = bookToRemove;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public void removeBook() throws SQLException
{
if (ds == null) {
throw new SQLException("ds is null; Can't get data source");
}
Connection conn = ds.getConnection();
if (conn == null) {
throw new SQLException("conn is null; Can't get db connection");
}
try {
System.out.print(bookToRemove);
PreparedStatement ord = conn.prepareStatement("Delete from APP.BOOK where Title = ?");
ord.setString(1, bookToRemove);
ord.execute();
bookToRemove = null;
} finally {
conn.close();
}
}
public void removeBook(String toRemove) throws SQLException
{
bookToRemove = toRemove;
removeBook();
}
public void addBook() throws SQLException {
if (ds == null) {
throw new SQLException("ds is null; Can't get data source");
}
Connection conn = ds.getConnection();
if (conn == null) {
throw new SQLException("conn is null; Can't get db connection");
}
try {
if(author != null && title != null)
{
PreparedStatement ord = conn.prepareStatement("INSERT INTO APP.BOOK (TITLE, AUTHOR, PRICE) "
+ " VALUES (?, ?, ?)");
ord.setString(1, title);
ord.setString(2, author);
ord.setDouble(3, Double.parseDouble(price));
ord.execute();
author = null;
title=null;
price = null;
}
} finally {
conn.close();
}
}
public void renderDisplay() {
display = true;
edit = false;
add = false;
remove = false;
}
public void renderEdit() {
display = false;
edit = true;
add = false;
remove = false;
}
public void renderAdd() {
display = false;
edit = false;
add = true;
remove = false;
}
public void renderRemove() {
display = false;
edit = false;
add = false;
remove = true;
}
public boolean isDisplay() {
return display;
}
public void setDisplay(boolean display) {
this.display = display;
}
public boolean isEdit() {
return edit;
}
public void setEdit(boolean edit) {
this.edit = edit;
}
public boolean isAdd() {
return add;
}
public void setAdd(boolean add) {
this.add = add;
}
public boolean isRemove() {
return remove;
}
public void setRemove(boolean remove) {
this.remove = remove;
}
public List<Book> getBooks() throws SQLException {
books.clear();
if (ds == null) {
throw new SQLException("ds is null; Can't get data source");
}
Connection conn = ds.getConnection();
if (conn == null) {
throw new SQLException("conn is null; Can't get db connection");
}
try {
PreparedStatement ps = conn.prepareStatement(
"select TITLE, AUTHOR, PRICE from BOOK"
);
ResultSet result = ps.executeQuery();
while (result.next()) {
Book b = new Book();
b.setAuthor(result.getString("AUTHOR"));
b.setTitle(result.getString("TITLE"));
b.setPrice(result.getDouble("PRICE"));
books.add(b);
}
} finally {
conn.close();
}
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
public String getSpecificTitle(int number) {
Book currentBook = (Book) books.get(number);
return currentBook.getTitle();
}
public String getSpecificAuthor(int number) {
Book currentBook = (Book) books.get(number);
return currentBook.getAuthor();
}
public double getSpecificPrice(int number) {
Book currentBook = (Book) books.get(number);
return currentBook.getPrice();
}
}
Again thank you so much for any help you may be able to give me
OK folks i have figured out my issue. i was clearing the array of books everytime i called get books in bookDatabase
public List<Book> getBooks() throws SQLException {
books.clear();
I changed this to an if check to see if the array was empty and it now works.
Tiny i also took your advise and moved my logic out of the get method for books. thank you for your help. I am slowly but surly getting better at JSF.
I have a rich:pickList, when submit values it still displays error: "Validation Error: Value is not valid". I also set breakpoint to debug (getAsobject), but after system invocation I had nothing.
BalusC said that I would implement the equals() method in my entities, or I have the entities in the web service, and I fill the right side of the picklist with data from this web service.
xHTML file
<h:form>
<rich:panel>
<h:panelGrid columns="2" styleClass="criteresSaisie"
rowClasses="critereLigne" columnClasses="titreColonne,">
<h:outputLabel for="libelleComplement" value=" "
size="20" />
<rich:pickList id="libelleComplement" sourceCaption="Compléments"
targetCaption="Compléments sélectionnés"
value="#{listeCmpltDispoModel.listeCmpltSelect}" size="15"
addText=">" addAllText=">>" removeText="<"
removeAllText="<<" listWidth="270px" listHeight="110px"
orderable="true">
<f:selectItems value="#{listeCmpltDispoModel.listeCmpltDispo}"
var="liste" itemLabel="#{liste.libelleComplement}"
itemValue="#{liste}" />
<f:converter converterId="cmpltsTitresConcerter" />
</rich:pickList>
</h:panelGrid>
<h:panelGroup>
<div align="right">
<h:panelGrid columns="8">
<h:commandButton value="Valider"
action="#{saisieCmpltsTitreCtrl.valider}" />
</h:panelGrid>
</div>
</h:panelGroup>
</rich:panel>
</h:form>
Converter
#FacesConverter(value="cmpltsTitresConcerter")
public class CmpltsTitresConcerter implements Converter
{
public Object getAsObject(FacesContext context, UIComponent component, String value)
{
ComplementsDispoSortieDTO cmpltSelect= new ComplementsDispoSortieDTO();
if(value != null)
{
cmpltSelect.setCdComplement(Long.parseLong(value));
//cmpltSelect.setLibelleComplement("aaa");
}
return cmpltSelect;
}
public String getAsString(FacesContext arg0, UIComponent arg1, Object obj)
{
String result = null;
if(obj != null)
{
result = String.valueOf(((ComplementsDispoSortieDTO) obj).getCdComplement());
}
return result;
}
}
Model
#ManagedBean(name = "listeCmpltDispoModel")
#SessionScoped
public class ListeCmpltDispoModel implements Serializable {
private static final long serialVersionUID = 1L;
private Long cdComplement;
private String libelleComplement;
private int nbCompl;
private List<ComplementsDispoSortieDTO> listeCmpltDispo ;
private List<ComplementsDispoSortieDTO> listeCmpltSelect ;
public ListeCmpltDispoModel() {
}
public Long getCodeComplement() {
return cdComplement;
}
public void setCodeComplement(Long cdComplement) {
this.cdComplement = cdComplement;
}
public String getLibelleComplement1() {
return libelleComplement;
}
public void setLibelleComplement1(String libelleCoplement) {
this.libelleComplement = libelleCoplement;
}
public Long getCdComplement() {
return cdComplement;
}
public void setCdComplement(Long cdComplement) {
this.cdComplement = cdComplement;
}
public String getLibelleComplement() {
return libelleComplement;
}
public void setLibelleComplement(String libelleComplement) {
this.libelleComplement = libelleComplement;
}
public List<ComplementsDispoSortieDTO> getListeCmpltDispo() {
return listeCmpltDispo;
}
public void setListeCmpltDispo(List<ComplementsDispoSortieDTO> listeCmpltDispo) {
this.listeCmpltDispo = listeCmpltDispo;
}
public int getNbCompl() {
return nbCompl;
}
public void setNbCompl(int nbCompl) {
this.nbCompl = nbCompl;
}
public List<ComplementsDispoSortieDTO> getListeCmpltSelect() {
return listeCmpltSelect;
}
public void setListeCmpltSelect(List<ComplementsDispoSortieDTO> listeCmpltSelect) {
this.listeCmpltSelect = listeCmpltSelect;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((cdComplement == null) ? 0 : cdComplement.hashCode());
result = prime
* result
+ ((libelleComplement == null) ? 0 : libelleComplement
.hashCode());
result = prime * result
+ ((listeCmpltDispo == null) ? 0 : listeCmpltDispo.hashCode());
result = prime
* result
+ ((listeCmpltSelect == null) ? 0 : listeCmpltSelect.hashCode());
result = prime * result + nbCompl;
return result;
}
#Override
public boolean equals(Object obj){
if(!(obj instanceof ComplementsDispoSortieDTO)){
return false;
}
return ((ComplementsDispoSortieDTO)obj).getCdComplement()==this.cdComplement;
}
}
The equals() method of your entity is not right. It's not only in the wrong class (the backing bean class instead of the model class), but it's also using == on an Object (the == on an object only tests the reference, not the internal value; as a starter, you should have experienced this mistake on String values already).
The == on a Long would only return true is the Long instance was created by Long#valueOf() or Long#parseLong() and the value is between -128 and 127. Anything else, including new Long(value) and those with values beyond the given "flyweight" range, return false.
As with every other Java object (such as your current one), you need equals() instead. Put it in the right class and implement it as follows:
public class ComplementsDispoSortieDTO {
private Long cdComplement;
// ...
#Override
public boolean equals(Object obj){
if (!(obj instanceof ComplementsDispoSortieDTO)){
return false;
}
return (cdComplement != null)
? cdComplement.equals(((ComplementsDispoSortieDTO) obj).cdComplement)
: (obj == this);
}
}
Note that I also added the missing reflexive obj == this. See also the javadoc for list of requirements.
See also:
Validation Error: Value is not valid
Right way to implement equals contract
I know which could be the solution.
You should store the list and selected element in properties and maintain them in the scope as long as the component is used.
hey I am using the following code to create the number of text fields as the user wants
<h:form>
<p>Number Of News <h:inputText value="#{news.noOfFields}" /></p>
<ui:repeat value="#{news.values}" var="item">
<hr/>
News #{item.no}
<h:inputText value="#{item.news}" /><br/>
</ui:repeat>
<hr/>
<h:commandButton styleClass="btn btn-blue" action="#{news.submit}" value="Save" />
</h:form>
The managed bean news has a class News as
#ManagedBean
#SessionScoped
public class News
{
private String noOfFields;
private List<NewsVO> values;
public News()
{
this.values = new ArrayList<NewsVO>();
}
public String submit() {
for(NewsVO newsVO : this.values)
{
System.out.println(newsVO.getNews());
System.out.println(newsVO.getNo());
}
return null;
// save values in database
}
public String getNoOfFields() {
return noOfFields;
}
public List<NewsVO> getValues() {
return values;
}
public void setValues(List<NewsVO> values) {
this.values = values;
}
public void setNoOfFields(String noOfFields) {
this.values = new ArrayList<NewsVO>();
try {
for(int i=0;i<Integer.valueOf(noOfFields);i++)
{
NewsVO newsVO = new NewsVO();
newsVO.setNo(i+1);
this.values.add(newsVO);
}
this.noOfFields = noOfFields;
}
catch(NumberFormatException ex) {
/*values = new String[1];*/
noOfFields = "1";
}
}
}
The NewsVO is just a javaBean class as follows
public class NewsVO
{
public int no;
public String news;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getNews() {
return news;
}
public void setNews(String news) {
this.news = news;
}
}
The problem is the values inside the input Text doesn't get reflected on pressing the save button. It gives me null, even though, I have written something inside all the textfields.
<h:inputText value="#{item.news}" />
Everytime you push the submit button, all setters in the bean are called (including setNoOfFields()). In this setter you are resetting your list, that's why you loose your values. Since you only need to modify your list if there is a size change, here is a simple way doing it :
#ManagedBean
#SessionScoped
public class News
{
private int noOfFields;
private List<NewsVO> values;
public News()
{
this.values = new ArrayList<NewsVO>();
}
public String submit()
{
for(NewsVO newsVO : this.values)
{
System.out.println(newsVO.getNews());
System.out.println(newsVO.getNo());
}
return null;
// save values in database
}
public int getNoOfFields()
{
return noOfFields;
}
public List<NewsVO> getValues()
{
return values;
}
public void setValues(List<NewsVO> values)
{
this.values = values;
}
public void setNoOfFields(int noOfFields)
{
if(noOfFields < this.noOfFields)
{
for(int i = this.noOfFields - 1;i >= noOfFields;i--)
{
getValues().remove(i);
}
}
else if(noOfFields > this.noOfFields)
{
for(int i = this.noOfFields;i < noOfFields;i++)
{
NewsVO newsVO = new NewsVO();
newsVO.setNo(i+1);
getValues().add(newsVO);
}
}
}
}
Note : I've also changed your noOfFields getter/setter for simple int, JSF will do the conversion for you.