Programmatically created html components in jsf managed beans - html

I have a following code:
<div id="mws-navigation">
<ul>
<li><p:commandLink
value="#{contentMB.msg.welcome_title.value}" actionListener="#{cleanUpMB.alChangeArea}"
styleClass="mws-i-24 i-home" action="#{welcomeMB.aLoadDashboard}" global="false" /></li>
<li><p:commandLink
value="#{contentMB.msg.layout_menu_measures.value}"
rendered="#{userSessionMB.measureEdit or userSessionMB.measureCreate}"
styleClass="mws-i-24 i-table-1" global="false" />
<ul>
<li><p:commandLink
value="#{contentMB.msg.layout_menu_mm_findMeasures.value}"
rendered="#{userSessionMB.measureEdit}"
actionListener="#{cleanUpMB.alChangeArea}"
action="#{chooseMeasureControllerMB.aChoose}" /></li>
<li><p:commandLink
value="#{contentMB.msg.layout_menu_mm_newMeasures.value}"
rendered="#{userSessionMB.measureCreate}"
actionListener="#{cleanUpMB.alChangeArea}"
action="#{newMeasureControllerMB.aNew}" /></li>
</ul>
</li>
</ul>
</div>
which I want to generate from the backing JSF managed bean. I know that for Primefaces exist java components that I can use and bind them as a model, but how can I generate pure HTML tags:
<ul>
<div>
...
?

A simple way would be to return some HTML from the backing bean:
#Named
#RequestScoped
public class HtmlController implements Serializable {
private static final long serialVersionUID = 1L;
public String getSomeHtml(){
return "<h1>Some HTML from a bean</h2>";
}
}
And paste this into the JSF part:
<h:outputText value="#{htmlController.someHtml}" escape="false" />
But I think for your case it would be better to create your own component, there you can also do some binding to backing beans. One example how to do that can be found here or take look at the tutorial of Java EE 6 .

Related

How to initialize an external reference in Thymeleaf?

If I had a Java class called for instance Buffet and one of its fields was something like:
#ManyToOne
private Chef chef
and I had to create a new Buffet object in an html form using Thymeleaf, how would I be able to refer to this chef field? At the moment my html looks like this:
<form th:action="#{/newBuffet}" method="POST" th:object="${buffet}">
<div>
<div>
<span><input type="text" th:field="*{name}" placeholder="name"/></span>
</div>
<div>
<span><input type="text" th:field="*{chef}" placeholder="chef"/></span>
</div>
<div>
<span><button type="submit">Invio<i class="material-icons">done</i></button></span>
</div>
</div>
</form>
and my controller like this:
#RequestMapping(value = "/newBuffet", method = RequestMethod.GET)
public String formBuffet (Model model) {
model.addAttribute("buffet", new Buffet());
return "newBuffet.html";
}
#RequestMapping(value = "/newBuffet", method = RequestMethod.POST)
public String addBuffet (#ModelAttribute("buffet") Buffet b, Model model) {
this.buffetService.save(b);
model.addAttribute("buffets", this.buffetService.listBuffets());
return "buffets.html";
}
the error it gives is, of course, because of the way Thymeleaf's input takes only strings whilst my input is an instance of my class Chef.

How to pass data from one Managed Bean to another? [duplicate]

This question already has answers here:
Creating master-detail pages for entities, how to link them and which bean scope to choose
(2 answers)
Closed 4 years ago.
I am developing a website using JSF 2.2 and Primefaces 6.1 where I have, initially, 2 pages: A "list" page, where I can show the data to the user, and a "create" page, where I can create new data or edit existing ones.
NOTE: "Cargo" means occupation.
list.xhtml:
...
<h:form>
<p:commandButton value="Cadastrar" styleClass="ui-button-sucesso" action="create.xhtml?faces-redirect=true"/>
</h:form>
...
<h:form>
<p:dataTable value="#{cargoListMB.listaCargo}" var="cargo" rowKey="#{cargo.codigo}" emptyMessage="Nenhum cargo encontrado" filteredValue="#{cargoListMB.listaCargoFiltro}">
<f:facet name="header">Tabela de Cargos</f:facet>
<p:column headerText="Código" sortBy="#{cargo.codigo}" filterBy="#{cargo.codigo}" filterPosition="top">
<h:outputText value="#{cargo.codigo}"/>
</p:column>
<p:column headerText="Nome" sortBy="#{cargo.nome}" filterBy="#{cargo.nome}" filterPosition="top" filterMatchMode="contains">
<h:outputText value="#{cargo.nome}"/>
</p:column>
<p:column headerText="Funcionários" sortBy="#{cargo.funcionariosNesteCargo}"filterBy="#{cargo.funcionariosNesteCargo}" filterPosition="top">
<h:outputText value="#{cargo.funcionariosNesteCargo}"/>
</p:column>
<p:column headerText="Editar">
<p:commandButton icon="fa fa-pencil" title="Editar" styleClass="ui-button-icone-apenas" action="create.xhtml?faces-redirect=true">
<f:param name="objcargo" value="#{cargo.codigo}"/>
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
CargoListMB.java:
#ManagedBean(name = "cargoListMB")
#ViewScoped
public class CargoListMB implements Serializable {
private List<Cargo> listaCargo;
private List<Cargo> listaCargoFiltro;
public List<Cargo> getListaCargo() {
if (listaCargo == null) {
listaCargo = CargoDAO.listarTodos(); //load data from database
}
return listaCargo;
}
public void setListaCargo(List<Cargo> listaCargo) {
this.listaCargo = listaCargo;
}
...
}
create.xhtml:
<h:form>
<f:metadata>
<f:viewParam name="objcargo" value="#{cargoCreateMB.cargo}" converter="cargoConverter"/>
<f:viewAction action="#{cargoCreateMB.inicializar()}"/>
</f:metadata>
<div class="ui-grid ui-grid-responsive">
<div class="ui-grid-row">
<div class="ui-grid-col-6">
<h1 class="if-page-title"><h:outputText value="#{cargoCreateMB.cargo.codigo == 0? 'Cadastro de Cargos' : 'Edição de cargo'}"/></h1>
</div>
<div class="ui-grid-col-6"></div>
</div>
<br/>
<div class="ui-grid-row">
<div class="ui-grid-col-12">
<div class="ui-grid-row">
<div class="ui-grid-col-1">
<p:outputLabel for="nome" value="Nome:"/>
</div>
<div class="ui-grid-col-3">
<p:inputText id="nome" placeholder="nome" value="#{cargoCreateMB.cargo.nome}" required="true""/>
</div>
<div class="ui-grid-col-8">
<p:message for="nome"/>
</div>
</div>
<br/>
<div class="ui-grid-row">
<div class="ui-grid-col-3">
<p:commandButton value="Salvar" actionListener="#{cargoCreateMB.salvar}" update="form" styleClass="ui-button-salvar"/>
</div>
<div class="ui-grid-col-9"></div>
</div>
</div>
</div>
</div>
</h:form>
CargoCreateMB.java
#ManagedBean(name = "cargoCreateMB")
#ViewScoped
public class CargoCreateMB implements Serializable {
private Cargo cargo;
public void salvar() {
try {
ControleCargo.insereCargo(cargo); //saves the 'occupation' on the database
MensagensUtil.mensagemInfo("Atenção", "Cargo inserido com sucesso");
} catch (RuntimeException e) {
MensagensUtil.mensagemInfo("Erro", "Erro ao inserir cargo");
System.out.println("Erro: " + e);
}
}
public void inicializar() {
//QUESTION!! : Due to a JSF page's life cycle, could I put this code on the constructor??
if (this.cargo == null) {
this.limpar();
}
}
private void limpar() {
cargo = new Cargo();
}
public Cargo getCargo() {
return cargo;
}
public void setCargo(Cargo cargo) {
this.cargo = cargo;
}
}
As you can see, I am trying to pass the selected 'occupation' from page list.xhtml to crate.xhtml using <f:param> and <f:viewParam> tags. When I click on button 'Cadastrar' (means 'register'), everything works fine (the "cargo" object is initially null, as expected), but when I click on the edit button, the "cargo.codigo" (occupation's ID) value, sent by the <f:param> tag, does not "arrive" to the "cargo" object. The converter ('cargoConverter') should be working fine, BUT, when I checked the String value that the method getAsObject was receiving, it was ALWAYS "0", no matter which occupation I choose on my list.
I also tried to send the "raw" data: Instead of using a converter, I sent the "cargo.codigo" value directly to a String field, but it was ALWAYS null.
Could someone help me discover what was my mistake? Also, if it is possible, is there another way to send data to other Managed Beans? Thanks in advance.
Edit: Based on Kukeltje's comments, I formatted my code (which can be seen above) and removed all the nested <h:form> elements BUT the problem still persists. Therefore, the answers on question How to use <h:form> in JSF page? didn't help at all and this question is not a duplicate.
Based on Kukeltje's comments and tips and the answers on this question, I managed to find my mistake: my <f:metadata> was indeed inside a <h:form>
tag. I removed it from there and it worked perfectly.

JSP Data table Limit number of rows on each div

I'm doing a page where i display some labels and input text field so the user can introduce some data and send it back to the server. But sometimes the server send back more than 50 rows of information. In this case the user need to scoll multiple times in order to see all the fields. I want to create 2/3 divs and each contains maybe ~20 fields so that all fields can be displayed without scrolling. Any idea?
Here is my code
<div class="container">
<div class="row">
<f:view>
<h:form>
<h:dataTable value="#{Message.bits}" var="bit">
<h:column>
<div class="col-lg-4">
<h:outputText value="#{bit.id} #{bit.name}" />
<div class="input-group">
<h:inputText styleClass="form-control" size="100"
maxlength="100" value="#{bit.value}" />
</div>
</p>
</div>
</h:column>
</h:dataTable>
</h:form>
</f:view>
</div>
</div>
Class Message -> A container of bits. It is a bean manager
#ManagedBean
#ViewScoped
public class Message implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2712306195992874273L;
private List<Bit> bits = null;
public List<Bit> getBits() {
return bits;
}
//Do more things
Bit class
public class Bit implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6341896264030346040L;
private String name = null;
private String value = null;
private int id = 0;
//Business logic
I can use html, css, any js framework, jsp,java.
Thanks for your time.
If I got your question right, you want to display your data like this:
1 4 7
2 5 8
3 6 9
Instead of this:
1
2
3
4
5
..
I don't know if this is the best solution but it works for me.
You can try the code below.
<div class="row">
<ui:repeat var="bit" value="#{message.bits}" varStatus="bitstatus">
<h:outputText escape="false" value="<div class='col-lg-4'>" rendered="#{(bitstatus.index + 1) % 20 eq 1}" />
<h:outputText value="#{bit.id} #{bit.name}" />
<div class="input-group">
<h:inputText styleClass="form-control" size="100" maxlength="100" value="#{bit.value}" />
</div>
<h:outputText escape="false" value="</div>" rendered="#{(productstatus.index + 1) % 5 eq 0}" />
</ui:repeat>
</div>

How to disable <p:tab>

I want to disable <p:tab> using <p:commandButton>
File.xhtml
<h:form id="tabUserModule">
<p:tabView value="#{listModule.toArray()}" var="car" id="tabView1" widgetVar="delg1">
<p:tab title="#{car[0].module}" id="styleChoix" disabled="#{disableTag.disableTa}" >
<p:tabView orientation="left" >
<p:tab title=" Prototype " >
<h:panelGrid >
<p:commandButton value="Disable" oncomplete="delg1.select(0)"
action="#{disableTag.buttonAction}" update=":tabUserModule:tabView1:styleChoix"/>
.....
Bean.java
#ManagedBean
#ViewScoped
public class DisableTag implements Serializable {
private static final long serialVersionUID = 7179479455651980518L;
private boolean disableTa=false;
public boolean isDisableTa() {
return disableTa;
}
public void setDisableTa(boolean disableTa) {
this.disableTa = disableTa;
}
public void buttonAction()
{
disableTa = true;
}
}
But when i execute this code all tab are disabled so how can i solve this issue plz?
i want to disable tab surrounded by orange
You should change your update attribute to
update=":tabUserModule:tabView1"
only instead of your original ":tabUserModule:tabView1:styleChoix"
This means you have to update the whole p:tabView element instead of a specific tab only. Because upon inspection of the rendered html, this is a disabled="false" of your tab having the <div> as the <p:tabView> and the <li> and <a> combination as your individual <p:tab>:
<div id="tabUserModule:tabView1" ...>
<li class="ui-state-default ui-corner-top" ...>
....
</li>
</div>
but with disabled="true" it is rendered as:
<div id="tabUserModule:tabView1" ...>
<li class="ui-state-default ui-tabs-selected ui-state-active ui-corner-top ui-state-disabled" ...>
....
</li>
</div>
Notice the addition of the ui-state-disabled in the class attribute of the <li> tag which causes it to be disabled.
Hope this helps.

how to get id of HTML element in JSF?

there are news titles.and user click on these titles.browser goes to the page which shoes the news of this title.i want to get data from database where id equals to elements id which is clicked.element gets id from database so i don't know id in advance.
<ui:repeat value="#{controller.sql.yenilikler}" var="list">
<a href="xeberShekil.xhtml" id="#{list.id}}">
#{list.basliq}
</a>
<br/>
</ui:repeat>
so i should
1.get the id of an element which is clicked
2.send this id into a variable in java class
3.send query which is get a data from database where id= the id of element
int id;
ResultSet rs= statement.executeQuery("select * from tableName where id="+id);
if an other algorithm propose please share.Tnx a lot
Pass values to managed bean using f:param, f:setPropertyActionListner or pass value directly using commandbutton's action="#{bean.someAction(value)}"
See JSF-2 Action Parameter for code snippets.
Edit to Code
Data table
<h:dataTable value="#{someManagedBean.categories}" var="cat">
<h:column>
<h:commandButton action="#{someManagedBean.edit(cat.id)}"
</h:column>
</h:dataTable>
Managed Bean
public void edit(id) {
doYourDBThing(id);
}
You can also use f:param and f:setPropertyActionListner. See the above link.