I have data loaded from DB, when click a command button:
<h:commandButton value="Show article content and comments" action="#{dataBean.activateArticleContentView}" actionListener="#{dataBean.loadCurrentArticle}">
<f:attribute name="articleId" value="#{article.id}"></f:attribute>
</h:commandButton>
@ManagedBean
@ViewScoped
public class DataBean implements Serializable {
...
private List<UserAcc> users;
private List<Article> articles;
private List<ArticleComment> articleComments;
private Article currentArticle;
public void loadComments(ActionEvent e) {
DataBaseUtil dbu = new DataBaseUtil();
int articleId = (Integer) e.getComponent().getAttributes()
.get("articleId");
articleComments = dbu.loadArticleComments(articleId);
}
public void loadCurrentArticle(ActionEvent e) {
DataBaseUtil dbu = new DataBaseUtil();
int articleId = (Integer) e.getComponent().getAttributes()
.get("articleId");
this.currentArticle = dbu.loadArticleById(articleId);
this.currentArticle.setComments(dbu.loadArticleComments(articleId));
}
...
it loads the article and it’s comments. Also textArea and a commandButton are rendered, on the same page, for adding a comment.
<h:inputTextarea value="#{persistenceBean.text}" style="height: 50px; width: 300px">
</h:inputTextarea>
<h:commandButton value="Save" actionListener="#{persistenceBean.saveComment}">
<f:attribute name="userName" value="#{loginBean.name}"></f:attribute>
<f:attribute name="articleId" value="#{dataBean.currentArticle.id}"></f:attribute>
</h:commandButton>
The command button activates this method in another bean (PersistenceBean):
public void saveComment(ActionEvent e){
int articleId = (Integer) e.getComponent().getAttributes().get("articleId");
String userName = (String) e.getComponent().getAttributes().get("userName");
DataBaseUtil dbu = new DataBaseUtil();
UserAcc user = dbu.loadUserByName(userName);
ArticleComment comment = new ArticleComment();
comment.setText(this.text);
Date postat = new Date();
comment.setPostat(postat.toString());
dbu.saveComment(articleId, user.getId(), comment);
}
My question is how to rerender the table with the comments, so that the change can be shown immediately. Now i need to back to the articles view and click the button that shows the article content and comments. Can i have more than one action listener for the button that adds the comment, int other words, how to use dataBean.loadCurrentArticle once again after add the comment.
Change
to
and inject
PersistenceBeaninDataBean(by@EJB, I assume?) so that you can do as follows inDataBean#saveComment():Unrelated to the concrete problem, there are way more elegant ways to pass attributes in JSF 2.x. See also How can I pass selected row to commandLink inside dataTable?