I am currently reworking an ADF Fusion Web application using Jdev v12.2.1.4.0 (Oracle 12c).
On one of the jsf pages I have a SelectOneChoice inside a table column. The jsf-implementation looks like this:
<af:column
headerText="#{ManagedBean.column5HeaderText}"
sortable="false"
visible="true"
id="c5">
<af:selectOneChoice
binding="#{ManagedBean.bindingErrorCaseSelectOneChoice}"
label="error case"
unselectedLabel="---"
autoSubmit="true"
id="soc1">
<f:selectItems value="#{ManagedBean.errorCases}" id="si1"/>
</af:selectOneChoice>
</af:column>
I left out the required attribute because it is not necessary for the process to select a value here.
The coherent parts of my ManagedBean.java are as following:
//declaring
private RichSelectOneChoice bindingErrorCasesSelectOneChoice;
private List<SelectItem> errorCases = new ArrayList<SelectItem>();
//...
//populating errorCases List from a database
public void getErrorCasesFromDB() {
errorCases= new ArrayList<SelectItem>();
try {
//HC is a helper class to connect to a specific database
Conection conn = HC.getConn();
PreparedStatement pstmt = conn.prepareStatement("some SQL");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
errorCases.add(new SelectItem("i"+ rs.getRow(), rs.getString(1)));
}
conn.close();
} catch(Exception e) {
e.printStackTrace();
}
}
As I run the jsf page the SelectOneChoices inside the table get rendered and all the expected items are enlisted. I am facing a problem whenever i try to access the selected item of the SelectOneChoice.
I want to read the value of the selectedItem when I hit a button on the page, so I figured I could leave out having to deal with that in a valueChangeListener, and did the following in my button action:
public void buttonSaveReceivedResults(ActionEvent actionEvent) {
//...
if (bindingErrorCaseSelectOneChoice.getValue != null) {
//... insert the selected value into an SQL statement
//in the case the unselected label is selected, skip
System.out.println(bindingErrorCasesSelectOneChoice.getValue().toString())
}
}
This block always gets skipped. Also when i inspected the process, the getValue() call always returned null, even if i select an item from the list.
Now i'm asking you guys, where is the missing part in the chain? Did I do the data bindings correctly. Do I access the elements in the wrong way? Thanks in advance.
The value attribute stores the output of af:selectOneChoice component. Since you have not added it, value returned was null.
Related
I am writing this program in which I am using preparedStatements to make changes to an SQL Database. However, the UPDATE query is not working.
Here is the code:
package financials;
import java.net.URL;
import java.util.ResourceBundle;
import java.sql.*;
public void initialize(URL url, ResourceBundle rb) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/finances","root","P#ssword");
con.setAutoCommit(true);// TODO
}
catch(Exception ae)
{
System.out.println("Error in connection !");
}
#FXML
private void SaveOrAdd(ActionEvent event) { //This is button which on click executes the following code
String Action=save.getText();
if(Action.equals("Add Account"))
{
String SBNumber=LinkedSB.getText();
String newAccountType=AccountTypeF.getText();
String newFHolder=FHolderF.getText();
String newSHolder=SHolderF.getText();
String newTHolder=THolderF.getText();
String Bankcode=BankCodeF.getText();
if(newAccountType.equals("")||newFHolder.equals("")||newSHolder.equals("")||newTHolder.equals(""))
{
update.setText("Please fill in all the fields !");
}
else
{
try
{
PreparedStatement pst=con.prepareStatement("INSERT INTO banklines (Bank_Code,Linked_SB_Account,Sb_Account_Type,First_Holder,Second_Holder,Third_Holder) VALUES (?,?,?,?,?,?)");
pst.setString(1,Bankcode);
pst.setString(2,SBNumber);
pst.setString(3,newAccountType);
pst.setString(4,newFHolder);
pst.setString(5,newSHolder);
pst.setString(6,newTHolder);
int a=pst.executeUpdate();
System.out.println(a); //This returns a 1
}
catch(Exception ae)
{
update.setText("Update Failed !");
}
}}
else
{
String SBNumber=LinkedSB.getText();
String newAccountType=AccountTypeF.getText();
String newFHolder=FHolderF.getText();
String newSHolder=SHolderF.getText();
String newTHolder=THolderF.getText();
String Bankcode=BankCodeF.getText();
if(newAccountType.equals("")||newFHolder.equals("")||newSHolder.equals("")||newTHolder.equals(""))
{
update.setText("Please fill in all the fields !");
}
else //This is the block in concern
{
try
{
//Here is where the issue starts !
PreparedStatement pst2=con.prepareStatement("UPDATE banklines SET Sb_Account_Type=?,First_Holder=?,Second_Holder=?,Third_Holder=? WHERE Linked_SB_Account=? AND Bank_Code=?");
pst2.setString(1,newAccountType);
pst2.setString(2,newFHolder);
pst2.setString(3,newSHolder);
pst2.setString(4,newTHolder);
pst2.setString(5,SBNumber);
pst2.setString(6,Bankcode);
pst2.executeUpdate();
int a=pst2.executeUpdate();
System.out.println(a); //This returns a 0
update.setText("Successfully Updated !");
}
catch(Exception ae)
{
update.setText("Update Failed !");
}
}
}
}
The problem is that no error is being thrown, that is, the output is always Successfully Updated. However, the changes are not being reflected on the database. I have tried executing the query UPDATE banklines SET Sb_Account_Type=?,First_Holder=?,Second_Holder=?,Third_Holder=? WHERE Linked_SB_Account=? AND Bank_Code=? separately as a query in mySQL workbench, and it returns no error. I have also ensured that no variable is left blank. In-spite of all this, the update is not working. What confused me even more is that the previous query in the if-else block, that is the INSERT query works perfectly, and the results are updated in the database as well.
I am using NetBeans 8.2 with jdk 1.8 and mysql-connector-java-8.0.21.
P.S. I have stuck to java naming conventions to the best of my knowledge, ensuring that I follow CamelCase notation wherever I could. Please edit my code or suggest changes if you feel that anything is wrong.
The column names of your insert statement don't match the order of the bind variables which means that your inserted record has the wrong account id values.
For example you set SBNumber as index 6 when it should be:
pst.setString(2,SBNumber);
It is also good practice to check the number of rows changed by updates so that you can make further asserts / checks on your actions:
int rows = pst.executeUpdate();
if (rows != 1) throw new RuntimeException("Failed to update account: "+ SBNumber);
In your case rows is set to 0 as the row to update is never found - because Linked_SB_Account is not matched.
Logic: Display drop down (data from TABLE_ONE) in page1.amx and based on the selection it needs to get data from TABLE_TWO, then render the retrieved data into page2.amx. Below is the sample which I have tried,
I have created service class ServiceClass.java in my service package and created DataControl (ServiceClassDC) for that class.
From my FirstPage.amx I'm calling service class method using valueChangeListener in drop down (Drop down value will be populated from DB, let's take TABLE_ONE ID). Below is the piece of code for this logic,
FirstPage.amx
<amx:selectOneChoice value="#{bindings.selectId.inputValue}" label="Select Id" id="soc1"
valueChangeListener="#{ServiceClass.callThisMethod}">
<amx:selectItems value="#{bindings.selectId.items}" id="si1"/>
</amx:selectOneChoice>
Based on the selection using WHERE condition, I got the list of objects in productList which is having the result set data.
ServiceClass.java
public void callThisMethod(ValueChangeEvent valueChangeEvent) {
System.out.println("Selected Value: "+valueChangeEvent.getNewValue());
String selectedValue = valueChangeEvent.getNewValue().toString();
ClassMappingDescriptor descriptor = ClassMappingDescriptor.getInstance(TableTwo.class);
DBPersistenceManager pm = getLocalPersistenceManager();
try{
StringBuffer sql = pm.getSqlSelectFromPart(descriptor);
sql.append(" WHERE ID='"+selectedValue+"'");
sql = pm.constructOrderByClause(sql, descriptor);
ResultSet set = pm.executeSqlSelect(sql.toString(), new ArrayList());
System.out.println("Result set >> "+set);
List productList = pm.createEntitiesFromResultSet(set, (List) descriptor.getAttributeMappingsDirect());
System.out.println("productList "+productList);
} catch(Exception exp){
System.out.println("Exception : "+exp);
}
}
Now, I want to display the List object data (productList) into SecondPage.amx screen. How to do this?
Please comment below, if you want any more details regarding this.
You need to expose your List productList in a public method (so provide a get method) and expose that method in a Data Control. You can then drag and drop it on your page.
Example:
public Product[] getProductArray() {
return (Product[]) productList.toArray();
}
Note that this is an example from a MAF version where Java 1.4 was used!
I would like to use p:rating component, to vote and save the value into the database (if it is already voted to be able to extract the value from the db later). In the Entity i have also comments fields and i would like if comments are already written to add only the vote so i sometimes i make merge instead of persist (if there is nothing for this request written in the DB).
I have the following code in my .xhtml page:
<h:form
rendered="#{not empty userRequestBean.request.hiredAgency.city}">
<p:rating value="#{userRequestBean.rating}" stars="10"
onRate="#{userRequestBean.rateAgency()}">
</p:rating>
</h:form>
In my bean I have:
#ManagedBean(name = "userRequestBean")
#SessionScoped
public class UserRequestBean implements Serializable {
private Integer rating; // Plus get and set methods
private TComment agencyComment = new TComment();
public void rateAgency() {
if (rating == null) return;
EntityManager em = HibernateUtil.getEntityManager();
if (!em.getTransaction().isActive())
em.getTransaction().begin();
Query queryAgencyComment = em.createQuery("select comment "
+ "from TRequest req join req.requestComments comment "
+ "where req.id = :requestId ");
Long requestId = (Long) request.getId();
queryAgencyComment.setParameter("requestId", requestId);
agencyComment = (TComment) queryAgencyComment.getSingleResult();
if (agencyComment.equals(null)) {
agencyComment = new TComment();
agencyComment.settRequest(request);
agencyComment.setCommentDate(new Date());
agencyComment.setAssessment(rating);
em.persist(agencyComment);
em.getTransaction().commit();
} else {
agencyComment.setAssessment(5);
em.merge(agencyComment);
em.getTransaction().commit();
}
}
But onRate, the method rateAgency is not executed. It is executed only once when the page is rendered. How can i implement this working?
The attribute onRate defines a JavaScript (client side) action, whilst you are trying to run a server method.
You need an ajax action instead:
<p:rating value="#{userRequestBean.rating}" stars="10" >
<p:ajax event="rate" listener="#{userRequestBean.rateAgency()}" />
</p:rating>
Useful links:
PrimeFaces showcase
A good JSF Tutorial (like Oracle's Java EE 7 Tutorial)
I have a Tabbed Layout in my application
Please see this Image
So as you can see in the above Image I've 2 Tables in 2-different Tabs in first tab (SALON STOCK tab)
i want to remove the selected row
what did is : removebutton's actionPerformed Method
int row_num =jTable4.getSelectedRow();
try{dtm_stock.removeRow(row_num);}
catch(ArrayIndexOutOfBoundsException e){
JOptionPane.showMessageDialog(this,"Please select a Product");
}
this works fine for the current tab(SALON TAB)
but how to implement same for the other Tab (Stock for Sale).
Further Details :
I have 2-table in the 2-diff tabs and bothe have 2-different TableModel (Default)
at initialization the data is set to null
after that the Data is retrieved from database and set to the corresponding TableModel.
now there is a remove button which will remove the selected row from table
i want to remove the selected row from tables irrespective of any Tab
CODE : initialization
jTable4 = new javax.swing.JTable();
dtm_stock = new DefaultTableModel(new Object [][] {
{null,null, null, null},
{null,null, null, null}
},
new String [] {
"ID","NAME", "PRICE", "QUANTITY"
});
jTable4.setModel(dtm_stock
);
ADDING DATA :
//-----ADD STOCK TO THE STOCK TABLE --------------//
try {
ResultSet r7 = con.createStatement().executeQuery("select * from stock");
while(r7.next()){
dtm_stock.insertRow(dtm_stock.getRowCount(),new Object[]{r7.getString("id"),r7.getString("p_name"),r7.getString("price"),r7.getString("qty")});
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this,e.toString());
}
if i'm adding the same TableModel to the other Table then the data goes to that table and the current goes blank:
this seems to have did the trick :`
int selectedIndex = jTabbedPane2.getSelectedIndex();
if(selectedIndex == 0 ){
int row_num =stock_table.getSelectedRow();
try{
dtm_stock.removeRow(row_num);
}
catch(ArrayIndexOutOfBoundsException/*|SQLException*/ e){
JOptionPane.showMessageDialog(this,"Please select a Product");
}
}//if
if(selectedIndex == 1){
int row_num =sale_Stock_table.getSelectedRow();
try{
dtm_sale_stock.removeRow(row_num);
}
catch(ArrayIndexOutOfBoundsException/*|SQLException*/ e){
JOptionPane.showMessageDialog(this,"Please select a Product");
}
}
from here :
enter link description here
if they share same model how can they have different data, please explain
You can control which columns to display in the view (JTable).
Look at the removeColumn(...) method of JTable. It removes a column from the view. However the data is still in the TableModel.
If I understand corectly you can put some flag which will hold value for current visible tab and use if statment to remove row from correct Model. On the other hand better solution would be creating some kind of controller. The controller would store active tab, and would have removeRow method. Switching tab would trigger event so controller would know from which tab delete row.
I got some troubles with some codes. Now I try to modify/delete personal information , but I enter an invalid value try modify/delete , it's still pop a new window . I dont know how to modify those code for i enter an invalid value , it will not pop a window .
I have other question . When I enter a valid value , the value cant pass to pop window , like I enter a name to go grab id value , the value cant pass to pop window , how can I reslove it . Thank all !
HTML
<h:panelGrid columns="3" cellspacing="20">
<h:outputLabel for="name" value="Modify Name"/> <p:inputText value="#{modify.enName}"/>
<h:commandButton value="Modify System" style="height:35px" onclick="window.open('#{modify.domodify()}','modify',
'width=500,height=400,status=yes,resizable=yes,scrollbars=yes') ; return false;"/>
</h:panelGrid>
Java Code
public String domodify() {
try {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.mycompany_SuneCoolingSystem_war_1.0-SNAPSHOTPU");
EmployeeJpaController jpaController = new EmployeeJpaController(null, emf);
EntityManager e = jpaController.getEntityManager();
Query q = e.createNamedQuery("Employee.findByEnName");
q.setParameter("enName", getEnName());
System.out.println(getEnName());
List resultList = q.getResultList();
Employee result = (Employee) resultList.get(0);
id = result.getId();
name = result.getName();
idNumber = result.getIdNumber();
constellation = result.getConstellation();
email = result.getEmail();
enName = result.getEnName();
rego="CRUD/Modify.xhtml";
} catch (Exception ex) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "No Man", ""));
rego = "index.xhtml";
}
return rego;
}
onclick="window.open('#{modify.domodify()}','modify', 'width=500,height=400,status=yes,resizable=yes,scrollbars=yes')
This code means when clicked, open a new window and perform the action to check what URL is returned. The windows is opened before any logic is executed.
You should perform an ajax call to the modify with f:ajax (or your component library equivalent, if you want) and use onevent to launch the correct javascript when the ajax calls ends in success and returning the expected value.
See JSF 2: How show different ajax status in same input? to see an example of dealing with onevent.