Filter for JSF table - jsf

I would like to add filter for JSF table and limit the values based on filter value.
<h:inputText id="search" value="#{accounts.searchString}"></h:inputText>
<h:commandButton value="Search" action="#{accounts.search()}">
<f:ajax execute="search" render="output"></f:ajax>
</h:commandButton>
I suppose that the best way will be to add the filter value into the SQL query:
SELECT * FROM CUSTOMERS ORDER BY %S %S offset ? limit ?
Full code: http://pastebin.com/eEeTWEqK
How I can implement this for the code into the link?
PS. I modified the code this way:
<div class="div_input_style">
<h:inputText id="search" class="input_style" value="#{accounts.searchString}"></h:inputText>
<h:commandButton class="theSpan" value="Search by title">
<f:ajax execute="search" render="output"></f:ajax>
</h:commandButton>
</div>
public List<AccountsObj> list(int firstRow, int rowCount, String sortField, boolean sortAscending) throws SQLException
{
String SqlStatement = null;
if (ds == null)
{
throw new SQLException();
}
Connection conn = ds.getConnection();
if (conn == null)
{
throw new SQLException();
}
String sortDirection = sortAscending ? "ASC" : "DESC";
SqlStatement = "SELECT * FROM ACCOUNT "
+ " WHERE ? IS NULL OR ? IN (USER_NAME, FIRST_NAME, LAST_NAME)"
+ " ORDER BY %S %S offset ? limit ? ";
String sql = String.format(SqlStatement, sortField, sortDirection);
PreparedStatement ps = null;
ResultSet resultSet = null;
List<AccountsObj> resultList = new ArrayList<>();
try
{
conn.setAutoCommit(false);
boolean committed = false;
ps = conn.prepareStatement(sql);
ps.setString(1, searchString);
ps.setString(2, searchString);
ps.setInt(3, firstRow);
ps.setInt(4, rowCount);
resultSet = ps.executeQuery();
resultList = ProcessorArrayList(resultSet);
conn.commit();
committed = true;
}
finally
{
ps.close();
conn.close();
}
return resultList;
}

Related

Auto fields liferay in custom portlet

I have a doubt.
I have a main.jsp that includes another 2 jsp and a submit button. Both of them are part of a form.
The second one includes an auto field with a validator:
<div id="groupwork-fields" >
<div class="lfr-form-row lfr-form-row-inline">
<div class="row-fields">
<aui:input fieldParam='name' id="repetibleName" cssClass="full-size"
name="<%=AwardConstants.FIELD_OTHERS_NAME%>"
label='<%=AwardConstants.LABEL_NAME %>'
value="">
<aui:validator name="custom" errorMessage="fill-name">
function (val, fieldNode, ruleValue) {
var result = true;
var selector = document.getElementById("<portlet:namespace/>select-group").value;
if (selector == 1 && val === "") {
result = false;
}
return result;
}
</aui:validator>
</aui:input>
<aui:input cssClass="full-size"
id="email0" fieldParam='email0'
name="email0"
label='<%=AwardConstants.LABEL_EMAIL %>'
value="">
<aui:validator name="maxLength">100</aui:validator>
<aui:validator name="email"></aui:validator>
<aui:validator name="custom" errorMessage="fill-email">
function (val, fieldNode, ruleValue) {
var result = true;
var name = document.getElementById("<portlet:namespace/>name0").value;
if (name !== "" && val === "") {
result = false;
}
return result;
}
</aui:validator>
</aui:input>
</div>
</div>
</div>
After validating those fields and pressing the submit button goes to the next method:
public void saveAutofieldData(ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException, SystemException {
String groupworkIndexes = actionRequest.getParameter("groupworkIndexes");
_log.info("::::::::::::::::groupworkIndexes:::::::::::::::::::::::" + groupworkIndexes);
/**
* Split the row index by comma
*/
String[] indexOfRows = groupworkIndexes.split(",");
_log.info("::::::::::::::::indexOfRows.length:::::::::::::::::::::::"+ indexOfRows.length);
for (int i = 0; i < indexOfRows.length; i++) {
String name = (actionRequest.getParameter("name"+ indexOfRows[i])).trim();
String email = (actionRequest.getParameter("email"+ indexOfRows[i])).trim();
_log.info("::::::::::::Name::::::::::::::" + name);
_log.info("::::::::::::Email::::::::::::::" + email);
}
}
The problem is when It tries to read: actionRequest.getParameter("groupworkIndexes"); I get null.
Thank you in advance
I finally got the solution.
All examples I've seen it have been with "actionRequest" to retrieve the data:
String groupworkIndexes = actionRequest.getParameter("groupworkIndexes");
String name = actionRequest.getParameter("name" + indexOfRows[i]));
But in my case i've used the following lines:
String name = (uploadPortletRequest.getParameter("name" + indexOfRows[i]));
String groupworkIndexes = (uploadPortletRequest.getParameter("groupworkIndexes"));
Not always we would get the prefered values with actionRequest

Load checked checkbox from database in JSF based on boolean

I am having dynamic Checkboxes from database and I need them to be checked on page load based on a boolean true or false:
My xhtml:
<h:selectManyCheckbox value="#{report.reports}">
<f:selectItems value="#{report.allreports}" />
</h:selectManyCheckbox>
My Boolean:
public boolean checkedBox(String workclass, String reportname) {
Connection conn;
int count = 0;
try {
conn = db.getDbConnection();
String sql = "select count(*)NUM from rep_access where user_work_class = ? and rep_name = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, workclass);
ps.setString(2, reportname);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
count = rs.getInt(1);
}
DBConnection.closeConn(conn);
} catch (SQLException asd) {
System.out.println(asd.getMessage());
} catch (IOException asd) {
System.out.println(asd.getMessage());
}
return count > 0;
}
How can I get My check boxes to be checked if the boolean return true. reportname is the value of the check box and workclass value is in the session.

JSF Target Unreachable, ''0'' returned null: javax.el.PropertyNotFoundException

a list of Objects :
private ArrayList<LegBeanForInsert> listOfLegs;
I show this array by using the notation with arrays: 0 , 1 , .... positional for example:
<p:selectOneMenu value="#{otcdEventsBean.listOfLegs[0].fixvar}"
effect="fade" style="width:100px; height:25px"
panelStyle="width:80px" >
<f:selectItem itemLabel="Select" itemValue="" />
<f:selectItems value="#{otcdEventsBean.fixedVariableCodes}"
itemValue="#{otcdEventsBean.listOfLegs[0].fixvar}" />
<p:ajax listener="#{otcdEventsBean.fixvarchange}" event="change" update="panelUpdate"/>
</p:selectOneMenu>
ERROR:
value="#{otcdEventsBean.listOfLegs[0].fixvar}": Target Unreachable, ''0'' returned null: javax.el.PropertyNotFoundException
in the constructor of the bean i do:
public void initLeg(){
for(int i=0;i<8;i++){
LegBeanForInsert beanLeg = new LegBeanForInsert();
beanLeg.setCallamount(new BigDecimal(0));
beanLeg.setFixvar("");
this.listOfLegs.add(beanLeg);
}
}
this method is called by another page and when the page is renderd dose not have problem the page:
public void setProduct(Object product1, Object product2) {
System.out.println("BEGIN::setProduct: " + (String) product2);
if (product1 instanceof EqdProduct) {
this.eqdProdToedit = (EqdProduct) product1;
} else if (product1 instanceof CURROPTRBTProduct) {
this.rbtProdType = (CURROPTRBTProduct) product1;
} else if (product1 instanceof COMAsianProduct) {
this.comAsianProd = (COMAsianProduct) product1;
} else if (product1 instanceof CRDProductType) {
this.crdProduct = (CRDProductType) product1;
} else if (product1 instanceof ComSwapProduct) {
firstLegComSw = (ComSwapProduct) product1;
if (product2 instanceof ComSwapProduct) {
System.out.println("Com Sawp second prod");
secondLegComSw = (ComSwapProduct) product2;
}
} else if (product1 instanceof List) {
// bisogna settare LegBeanForInsert, LE GAMBE SONO 8 !!
List<?> legs = (List<?>) product1;
String s = (String) product2;
System.out.println("setProduct 2nd arg: " + product2);
if (s.equals("Legs")) {
for (int i = 0; i < legs.size(); i++) {
Leg leg = (Leg) legs.get(i);
LegBeanForInsert beanLeg = new LegBeanForInsert();
beanLeg.setCallamount(new BigDecimal(leg.getCallamount()));
beanLeg.setCallcurrency(leg.getCallcurrency());
beanLeg.setCallmaturity(leg.getCallmaturityNumber());
beanLeg.setCodintord(leg.getCodintord());
beanLeg.setDayconvention(leg.getDayconvention());
beanLeg.setEnddate(leg.getEnddate());
beanLeg.setEventcode(leg.getEventcode());
beanLeg.setEventtype(leg.getEventtype());
beanLeg.setExercisemode(leg.getExercisemode());
beanLeg.setFixvar(leg.getFixvar());
beanLeg.setEndDate(leg.getFmtenddate());
beanLeg.setStartDate(leg.getFmtstartdate());
beanLeg.setFrequency(leg.getFrequency());
beanLeg.setFrequencymultiplier(leg.getFrequencymultiplier());
beanLeg.setFrequencyunit(leg.getFrequencyunit());
beanLeg.setInareas(leg.getInareas());
beanLeg.setIndexname(leg.getIndexname());
beanLeg.setMargin(leg.getMargin());
beanLeg.setNotional(leg.getNotional());
beanLeg.setNumber(leg.getNumber());
beanLeg.setOptioncashdelivery(leg.getOptioncashdelivery());
beanLeg.setOptionmaturity(leg.getOptionMatirityNumber());
beanLeg.setOptiontype(leg.getOptiontype());
beanLeg.setPaycurrency(leg.getPaycurrency());
beanLeg.setPutamount(leg.getPutamount());
beanLeg.setPutcurrency(leg.getPutcurrency());
beanLeg.setPutmaturity(leg.getPutMatirityNumber());
beanLeg.setQuantityunit(leg.getQuantityunit());
beanLeg.setRate(leg.getRate());
beanLeg.setRateconvention(leg.getRateconvention());
beanLeg.setSign(leg.getSign());
beanLeg.setStartdate(leg.getStartdate());
beanLeg.setStrike(leg.getStrike());
this.listOfLegs.add(beanLeg);
}
} else {
System.out.println("MoneyD 2nd arg: " + product2);
for (int i = 0; i < legs.size(); i++) {
LegMoneyDeal leg = (LegMoneyDeal) legs.get(i);
this.legMoneyD.add(leg);
}
}
} else {
// non nè nessuno di quelli bisogna settare a null tutto quanto
otcdEvents = new OtcdEvents();
crdProduct = new CRDProductType();
firstLegComSw = new ComSwapProduct();
secondLegComSw = new ComSwapProduct();
comAsianProd = new COMAsianProduct();
rbtProdType = new CURROPTRBTProduct();
listOfLegs = new ArrayList<LegBeanForInsert>();
legMoneyD = new ArrayList<LegMoneyDeal>();
eqdProdToedit = new EqdProduct();
}
}
the constructor :
public OtcdEventsBean() {
try {
Context ctx = new InitialContext();
otcdEvents = new OtcdEvents();
crdProduct = new CRDProductType();
firstLegComSw = new ComSwapProduct();
secondLegComSw = new ComSwapProduct();
comAsianProd = new COMAsianProduct();
rbtProdType = new CURROPTRBTProduct();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/myoracleDS");
rederField = true;
listOfLegs = new ArrayList<LegBeanForInsert>();
initLeg();
eqdProdToedit = new EqdProduct();
legMoneyD = new ArrayList<LegMoneyDeal>();
legMoneyD.add(new LegMoneyDeal());
legMoneyD.add(new LegMoneyDeal());
fieldsEditingDisabled = false;
loginBean = (LoginBean) FacesContext.getCurrentInstance().getApplication().evaluateExpressionGet(FacesContext.getCurrentInstance(), "#{loginBean}", LoginBean.class);
setFixedVariableCodes(new String[2]);
getFixedVariableCodes()[0] = "Fixed";
getFixedVariableCodes()[1] = "Variable";
setSignPremiumCodes(new String[2]);
signPremiumCodes[0] = "Pay";
signPremiumCodes[1] = "Receive";
setFrequencyUnitCodes(new String[4]);
frequencyUnitCodes[0] = "day";
frequencyUnitCodes[1] = "week";
frequencyUnitCodes[2] = "month";
frequencyUnitCodes[3] = "year";
setCashDeliveryCodes(new String[2]);
cashDeliveryCodes[0] = "C";
cashDeliveryCodes[1] = "D";
setOptionTypeCodes(new String[2]);
optionTypeCodes[0] = "CALL";
optionTypeCodes[1] = "PUT";
} catch (NamingException e) {
e.printStackTrace();
}
}
full bean code:
http://pastebin.com/EbfuSwHN
How is the init method called. Maybe that is not getting called? I do not see a new ArrayList on the definition. When do you call new on ArrayList? You should be getting a null pointer exception in the init method. You could add the new ArrayList to the beginning of the init method before the loop. Remember also that set methods get called multiple times in JSF so you should limit the code in the set method.

Jsf datatable writes my data 3 times

I am trying to learn JSF and i have a problem with datatable.
I get datas from database and add them to my list and try to show them in my page. It write datas 3 times. Why is it? Here is my code...
here is related part of bean..
public ArrayList<videos> getVideoss() {
Connection con1 = null;
PreparedStatement pst1 = null;
ResultSet rs1 = null;
String url1 = "jdbc:postgresql://localhost:5432/db";
String user1 = "postgres";
String password11 = "123";
try {
Class.forName("org.postgresql.Driver");
con1 = DriverManager.getConnection(url1, user1, password11);
pst1 = con1
.prepareStatement("SELECT video_name FROM videos WHERE video_course = '"
+ selectedCourse + "';");
rs1 = pst1.executeQuery();
while (rs1.next()) {
videoss.add(new videos(rs1.getString(1)));
}
System.out.println(videoss.size());
.....
xhtml file
<h:dataTable value="#{videoSearch.videoss}" var="videos">
<h:column>
<f:facet name="header">Video Name</f:facet>
#{videos.videoName}
</h:column>
</h:dataTable>
when i look the size of the list it goes like 6 , 12 , 18.. but it should be 6..
Thanks for your support..
As I commented, you are recreting the list every time the getter is called, so the list is growing because you are not clearing it anywhere. Here is a better way to do it :
// Will be called only one time
#PostConstruct
public init()
{
Connection con1 = null;
PreparedStatement pst1 = null;
ResultSet rs1 = null;
String url1 = "jdbc:postgresql://localhost:5432/Thesis";
String user1 = "postgres";
String password11 = "123";
videoss = new ArrayList();
try
{
Class.forName("org.postgresql.Driver");
con1 = DriverManager.getConnection(url1, user1, password11);
pst1 = con1.prepareStatement("SELECT video_name FROM videos WHERE video_course = '" + selectedCourse + "';");
rs1 = pst1.executeQuery();
while (rs1.next())
{
videoss.add(new videos(rs1.getString(1)));
}
System.out.println(videoss.size());
//.....
}
catch(Excepption e)
{
e.printStackTrace();
}
}
public ArrayList<videos> getVideoss()
{
return videoss;
}

How to do filter in jsf datatable?

I need to do the filter in the datatable.
I have two dropdown and first is just static values..like filter by name,dob,age.Based on that open second dropdown and do the filter display the values.
<ice:selectOneMenu size="12" onchange="this.form.submit()"
partialSubmit="true" id="filterByPastDue"
valueChangeListener="#{details.filterByListener}">
<f:selectItem itemLabel="None" itemValue="1" />
<f:selectItem itemLabel="Name" itemValue="2" />
<f:selectItem itemLabel="Age" itemValue="3" />
<f:selectItem itemLabel="DOB" itemValue="4" />
<ice:selectOneMenu binding="#{person.selectFilterItems}" size="12" id="OpenFilterMenu" rendered="false">
In my mangebean have logic to get values in second drop down values.
public void filterByListener(ValueChangeEvent valueChangeEvent) {
int filterBy = Integer
.parseInt((String) valueChangeEvent.getNewValue());
switch (filterBy) {
case 1: {
filterItems = null;
filterItems = new HashSet<SelectItem>();
filterOptions = null;
filterOptions = new HashSet<String>();
outputTextFor = false;
selectFilterItems.setRendered(false);
break;
}
case 2: {
// clearing arraylist
filterItems = null;
filterItems = new HashSet<SelectItem>();
filterOptions = null;
filterOptions = new HashSet<String>();
// loading arrayList
for (int i = 0; i < person.size(); i++) {
filterOptions.add(person.get(i).getName()
.toString());
}
Iterator it = filterOptions.iterator();
while (it.hasNext()) {
String s = (String) it.next();
filterItems.add(new SelectItem(s, s));
}
// rendering components
outputTextFor = true;
selectFilterItems.setRendered(true);
break;
}
case 3: {
// clearing arraylist
filterItems = null;
filterItems = new HashSet<SelectItem>();
filterOptions = null;
filterOptions = new HashSet<String>();
// loading arrayList
for (int i = 0; i < person.size(); i++) {
filterOptions.add(person.get(i).getAge());
}
Iterator it = filterOptions.iterator();
while (it.hasNext()) {
String s = (String) it.next();
filterItems.add(new SelectItem(s, s));
}
// rendering components
outputTextFor = true;
selectFilterItems.setRendered(true);
break;
}
case 4: {
// clearing arraylist
filterItems = null;
filterItems = new HashSet<SelectItem>();
filterOptions = null;
filterOptions = new HashSet<String>();
// loading arrayList
for (int i = 0; i < person.size(); i++) {
filterOptions.add(person.get(i).getDOB());
}
Iterator it = filterOptions.iterator();
while (it.hasNext()) {
String s = (String) it.next();
filterItems.add(new SelectItem(s, s));
}
// rendering components
outputTextFor = true;
selectFilterItems.setRendered(true);
break;
}
default: {
// clearing arrayList
filterItems = null;
filterItems = new HashSet<SelectItem>();
filterOptions = null;
filterOptions = new HashSet<String>();
outputTextFor = false;
selectFilterItems.setRendered(false);
break;
}
}
}
Now i got the second drop down values what in my datatable.
Now, how to get the filter values display in the datatable.I having person object and need to display the datatables which ever selected in the second drop down.
You need to preset the property associated the value attribute of the h:dataTable with the desired datamodel. You could do that in the action method of the submit button or valueChangeListener method of the second dropdown. E.g.
public void submit() {
this.dataModel = getDataModelSomehow(filterBy, filterOption);
}

Resources