I don't have any idea what approach and how I should start coding to get the id
of a specific object item when a form button is clicked.
The Product Id values showing are primary keys of the product table I created. I'm coming from Swing programming and in Swing I can easily use the JLabel.getText();
to get the product Ids 1,4,5,6
shown on the screenshot. But I guess it's different with JSF.
Also, these object values are contained in a ui:repeat
loop
frames.xhtml
<ui:repeat value="#{frameBean.all}" var="f" varStatus="loop">
<h:outputText escape="false" rendered="#{loop.index % 3 == 0}" />
<div >
<div class="col-sm-6 col-md-3">
<div class="thumbnail clearfix">
<img src="..." alt="frame image placeholder" width="240" height="180"/>
<div class="caption">
<p>
<h:outputLabel>Product ID: </h:outputLabel>
<h:outputText value="#{f.product_id}"/>
</p>
<p><h:outputLabel value="#{f.name}"/></p>
<p><h:outputText value="#{f.description}"/></p>
<p>
<h:panelGroup rendered="#{login.userRole eq 'customer' or login.userRole eq null}">
<a href="#" class="btn btn-primary pull-right" role="button">Add To Cart</a>
</h:panelGroup>
</p>
</div>
</div>
</div>
</div>
<h:outputText escape="false" rendered="#{loop.last or (loop.index + 1) % 3 == 0}" />
</ui:repeat>
Surely, I can use the f.product_Id
but how can I get a specific Id if Add To Cart button is clicked?
Here's the implementation containing the getAll()
frames method
public List<Frame> getAll() throws SQLException {
List<Frame> list = new ArrayList<>();
PreparedStatement ps = null;
try {
String SQL = "select product_id, name, description, price_per_sqft, material from product where isFrame = 1";
ps = con.prepareStatement(SQL);
//get customer data from database
ResultSet result = ps.executeQuery();
while (result.next()) {
Frame frame = new Frame();
frame.setProduct_id(result.getInt("product_id"));
frame.setName(result.getString("name"));
frame.setDescription(result.getString("description"));
frame.setPrice_per_sqft(result.getDouble("price_per_sqft"));
frame.setMaterial(result.getString("material"));
//store all data into a List
list.add(frame);
}
} catch (SQLException | HeadlessException e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
For the purpose of obtaining the product Id of the frame I'm thinking of creating an addToCart(int aProductId)
method. It will require aProductId
argument.
Thank you.
You can use f:param component for store the product id
<p>
<h:outputLabel>Product ID: </h:outputLabel>
<h:outputText value="#{f.product_id}"/>
<f:param name="productId" value=""#{f.product_id}""></f:param>
</p>
and later in the bean you can get the value by using FacesContext
String propertyId = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
.get("productId");