Clear Date Selection using Primefaces Calendar - jsf-2

Is there any way to clear the date selection using prime faces calendar?
<p:calendar pattern="MM/dd/yyyy" navigator="true" id="endDate" for="endDate"
readonlyInput="true" mindate="#{manageMarketingProgramsBean.currentDate}" showOn="button">
<f:convertDateTime pattern="MM/dd/yyyy" timeZone="America/New_York" />
</p:calendar>
I have readonlyInput="true" because I dont want user to type the date. I force them to pick the date from the calendar, there needs to be another way to provide user the ability to clear the date selected. Please let me know how can I achieve this?

The first approach that comes into my mind would be:
<p:calendar readonlyInput="true" widgetVar="calendarWidget"/>
<p:commandButton value="Reset" onclick="calendarWidget.setDate(null)"/>

This worked for me
<p:calendar widgetVar="calendarWidget" pattern="MM/dd/yyyy" />
<p:commandButton value="Reset" onclick="PF('calendarWidget').setDate(null)"
type="button" />

Primefaces for the calendar component have this property: showButtonBar.
If you set it to true like this:
<p-calendar
appendTo="body"
formControlName="someControl"
id="someID"
[maxDate]="someMaxDate"
[showButtonBar]="true"
[showIcon]="true"
></p-calendar>
Then it will display two buttons on the calendar component. Today and Clear.
Hope it helps somebody.

HTML
<p:calendar
yearRange="c-100:c+100"
readonlyInput="true"
pattern="dd/MM/yyyy"
id="identity"
navigator="true"
mindate="today"
widgetVar="dateWidget"
value="#{bean.fieldname}"
/>
JS
function name() {
var mainID = prefix + collpaseID;
-
-
-
-
clearCalendar(mainID,event);
}
function clearCalendar(collapseId) {
try {
allElements =
document.getElementById(collapseId).getElementsByClassName('hasDatepicker');
for (i = 0, n = allElements.length; i < n; ++i) {
allElements[i].setAttribute('onkeyup',
'clearDate("'+allElements[i].id+'", event)');
}
}
catch(e) {}
}
function clearDate(fieldID, e) {
try{
// 8 - backspace key, 46 - delete key
if(e.keyCode == 8 || e.keyCode == 46) {
//PF(getWidgetVarById(collapseId)).setDate(null);
document.getElementById(fieldID).value="";
}
}
catch(e){}
}

<p:calendar
widgetVar="calendarWidgetStart"
/>
<p:calendar
widgetVar="calendarWidgetEnd"
/>
<p:commandLink
value="Action"
action="#{entity.action}"
onclick="setTimeout('remoteCommand();', 100);"
/>
<p:remoteCommand
name="remoteCommand"
update="#form"
onstart="clearCalendarWidget();"
/>
<script>
function clearCalendarWidget() {
$( PF('calendarWidgetEnd').setDate(null) );
$( PF('calendarWidgetStart').setDate(null) );
}
</script>

Related

Show/Hide components in primefaces 5/JSF 2.2 [duplicate]

This question already has an answer here:
Why do I need to nest a component with rendered="#{some}" in another component when I want to ajax-update it?
(1 answer)
Closed 7 years ago.
I thought this would be easy but I just cannot get it. I have a drop down and based on selection, I should be able to show/Hide another drop down based on a boolean. By default the boolean is false and only when it is true should the second drop down be rendered:
My page:
<h:outputLabel value="Select Report: "/>
<p:selectOneMenu value="#{daily.reportname}" id="sector" style="width: 250px;">
<f:selectItem itemLabel="ALL" itemValue="ALL" />
<f:selectItems value="#{daily.reportType()}"/>
<p:ajax event="change" update="branchrender" listener="#{daily.selectedReport()}" />
</p:selectOneMenu>
<h:panelGroup id="branchrender" rendered="#{daily.showBranchDimension}">
<h:outputText value="Branch" />
<p:selectOneMenu value="#{accounts.branchs}" id="branch" style="width: 250px;">
<f:selectItem itemLabel="ALL" itemValue="ALL" />
<f:selectItems value="#{dimensions.branchCode()}"/>
</p:selectOneMenu>
</h:panelGroup>
My selected report Method:
public void selectedReport() {
if (reportname.startsWith("cust_")) {
custrepname = reportname;
useBranch = pr.getCustRepProperties(custrepname + ".bi").getProperty("bi.useBranchDim");
showBranchDimension = useBranch.equalsIgnoreCase("true");
System.out.println("HERE: " + showBranchDimension);
} else {
custrepname = null;
}
}
showBranchDimension is a boolean having getter and setter:
public boolean isShowBranchDimension() {
return showBranchDimension;
}
public void setShowBranchDimension(boolean showBranchDimension) {
this.showBranchDimension = showBranchDimension;
}
Am I missing something? The System.out.println prints true but the component is NOT rendered.
You have to make the rendered component a rendered free because it must be exist when you submit the ajax request to server add another container to branchrender and move the rendered id to it
<h:panelGroup id="branchrender">
<h:panelGroup rendered="#{daily.showBranchDimension}">
<h:outputText value="Branch" />
<p:selectOneMenu value="#{accounts.branchs}" id="branch" style="width: 250px;">
<f:selectItem itemLabel="ALL" itemValue="ALL" />
<f:selectItems value="#{dimensions.branchCode()}"/>
</p:selectOneMenu>
</h:panelGroup>
</h:panelGroup>
See more about this.
I think problem could be with the way your implemented the p:ajax component. See the comments of p:ajax listener method not invoked.

How to pass a value on selected row change?

I have this permanent problem, I have a Datatable with value="#{myBean.Items}" var="itms", and I want to pass the selected item to my bean class.
In columns, we use <f:setPropertyActionListener value="#{itms}" target="#{myBean.selectedrow}" /> to pass the value, but I want it for Rows.
How to do that?, and where to put this listener?.
Thank you very much.
What richface version are you using?
For richfaces 4.3.x, the following example might do the trick:
XHTML:
<rich:extendedDataTable
id="myTable"
value="#{crudBean.rows}"
var="rowItem"
rowClasses="odd-row, even-row"
selection="#{crudBean.actionForm.selection}"
rows="#{crudBean.actionForm.occurrences}"
rowKeyVar="idx"
>
<a4j:ajax event="selectionchange"
listener="#{crudBean.actionForm.selectionListener}"
immediate="true" />
<rich:column width="100px" styleClass="#{rowItem.className}">
...stuff...
</rich:column>
<rich:column width="173px" styleClass="#{rowItem.className}">
...stuff...
</rich:column>
</rich:extendedDataTable>
The following code made sure the even got fired on row selection change:
<a4j:ajax event="selectionchange"
listener="#{crudBean.actionForm.selectionListener}"
immediate="true" />
The bean:
public void selectionListener(AjaxBehaviorEvent event) {
UIExtendedDataTable currentDataTable = (UIExtendedDataTable) event.getComponent();
Object originalKey = currentDataTable.getRowKey();
// debug log statement
log.debug("selectionListener() - rowKey = {} ", originalKey);
// debug log statement
if (log.isDebugEnabled()) {
log.debug("\n selectionListener() - rowIndex = {}", currentDataTable.getRowIndex());
}
if (currentDataTable.isRowAvailable()) {
// selectionItems.add(dataTable.getRowData());
IDataRow rowValue = transform((IDataGridRow)currentDataTable.getRowData());
changeActiveRow(rowValue);
}
}

How to get non-integer value from <p:slider>

I am trying to get Float value from primefaces slider. But, it seems does't support Non Integer value.
I have try by setting step - attribute, no improvement.
Here is my JSF code:
<h:panelGrid>
<h:panelGrid columns="2" style="margin-bottom:10px">
<p:outputLabel value="Interest Rate : "/>
<p:inputText id="intVal" value="#{primeSlider.interest}">
<f:convertNumber minFractionDigits="2" />
</p:inputText>
</h:panelGrid>
<p:slider id="interestSlider" for="intVal" minValue="5" maxValue="25" step="1" style="width:500px;" />
</h:panelGrid>
It is possible to get Non-Integer value like float,double from primefaces slider?
If so, How to do that?
It's not that complicated to handle the slider yourself. Check this sample code:
<h:form id="form">
<h:panelGrid>
<p:inputText id="intVal" value="#{primeSlider.interest}" widgetVar="iVar">
<f:convertNumber minFractionDigits="2" />
</p:inputText>
<div id="slider"></div>
<script>
$(function() {
jQuery("#slider").slider({
range: "min",
value: 37,
step: 0.25,
min: 1,
max: 700,
slide: function(event, ui) {
jQuery(iVar.jqId).val(ui.value);
}
});
jQuery(iVar.jqId).val(jQuery("#slider").slider("value"));
});
</script>
<p:commandButton value="Send" />
</h:panelGrid>
<p:outputPanel autoUpdate="true">
#{primeSlider.interest}
</p:outputPanel>
</h:form>

PrimeFaces - Dynamic menuItem

Considering the following code, it displays a table with one column and a filter to display the active/inactive records.
How can I disable the menuitem 'Inactive' based on the value selected in the filter? In other words if the the filter value is 'inactive', the 'Inactivate' menu should be disabled.
<p:contextMenu for="ratingScaleTable" id="RsContextMenuId">
<p:menuitem value="Edit" update=":templateForm:tabView, :templateForm:dirtyFlag" icon="ui-icon-search" action="#{ratingScaleBK.edit}" />
<p:menuitem id="inactivate" value="Inactivate" icon="ui-icon-close" action="#{ratingScaleBK.inactivate}" disabled="#{ratingScaleBK.selectedRatingScale.active==0}" />
<p:menuitem value="Activate" update=":templateForm:tabView" icon="ui-icon-close" action="#{ratingScaleBK.activate}"/>
<p:menuitem value="View Archive" update=":templateForm:tabView" icon="ui-icon-close"/>
</p:contextMenu>
<p:dataTable id="ratingScaleTable" widgetVar="tableWidget"
value="#{ratingScaleBK.ratingScaleList}" var="item1"
selectionMode="single"
selection="#{ratingScaleBK.selectedRatingScale}"
rowKey="#{item1.name}"
rendered="#{not empty ratingScaleBK.ratingScaleList}"
filteredValue="#{ratingScaleBK.filteredRatingscale}">
<p:ajax event="rowSelect" process="ratingScaleTable" listener="#{ratingScaleBK.edit}" update=":templateForm:tabView, :templateForm:dirtyFlag, :templateForm:tabView:RsContextMenuId " />
<p:column id="activeCol" filterBy="#{item1.active}"
filterOptions="#{ratingScaleBK.activeOptions}"
filterMatchMode="exact" width="30">
<h:outputText value="#{item1.active}" />
</p:column>
</p:dataTable>
Right now this code doesn't work, the contextMenu is never updated on rowSelect (the menu item 'Inactive' is always enabled). I guess the right click event on a specific row to display the menu doesn't really trigger the rowSelect event even if the row gets highlighted.
What is the proper way to do that?
I ended up using this solution from PF forum:
<p:contextMenu for="ratingScaleTable" id="RsContextMenuId" widgetVar="ctxMenu" beforeShow="return true;">
<p:dataTable id="ratingScaleTable" widgetVar="tableWidget"
...
<p:ajax event="rowSelect" process="ratingScaleTable" listener="#{ratingScaleBK.edit}" update=":templateForm:tabView, :templateForm:dirtyFlag, :templateForm:tabView:RsContextMenuId" />
<p:ajax event="contextMenu" update=":templateForm:tabView:RsContextMenuId" oncomplete="ctxMenu.show(currentEvent);"/>
and the associated JavaScript:
<script type="text/javascript">
var currentEvent;
$(document).ready(function() {
PrimeFaces.widget.ContextMenu.prototype.show = function(e) {
//hide other contextmenus if any
$(document.body).children('.ui-contextmenu:visible').hide();
if(e) {
currentEvent = e;
}
var win = $(window),
left = e.pageX,
top = e.pageY,
width = this.jq.outerWidth(),
height = this.jq.outerHeight();
//collision detection for window boundaries
if((left + width) > (win.width())+ win.scrollLeft()) {
left = left - width;
}
if((top + height ) > (win.height() + win.scrollTop())) {
top = top - height;
}
if(this.cfg.beforeShow) {
this.cfg.beforeShow.call(this);
}
this.jq.css({
'left': left,
'top': top,
'z-index': ++PrimeFaces.zindex
}).show();
e.preventDefault();
};
});
</script>
Try it with the contextMenu event:
<p:contextMenu for="ratingScaleTable" id="RsContextMenuId" widgetVar="ctxMenu">
...
</p:contextMenu>
<p:dataTable ... >
...
<p:ajax event="contextMenu" process="ratingScaleTable" listener="#{ratingScaleBK.edit}" update=":templateForm:tabView, :templateForm:dirtyFlag, :templateForm:tabView:RsContextMenuId" oncomplete="PF('ctxMenu').show();" />
...
</p:dataTable>

Conditional Submit through h:commandButton

We are using JSF 2.0 in our project. Apart from Mojara, we are using Primefaces 3.3 forsome components.
we have a Requirement in our project that we HAVE to do Javascript validations (as part of client side validation) and then only the form submit should happen. The Validation done by JSF will anyway happen (at server side). But the Javascript validtions should also be there.
This was the reason I had asked this question but got no comments.
I am therefore implementing the JavaScript validations and this brings me to the actual problem i am facing.
I have JS functions to do basic validations like "Required" fields, length check etc and calling them at appropiate time (like onblur). But if the user just leaves all the fields empty or does not go into some fields at all(thereby not triggering events like onblur) and clicks on the submit button, these fields are missed out for JS validations.
So how do i conditionally submit the form after all the JS validaitions are done?
Note that we have to use f:ajax for form submit.
I tried the onsubmit function of the form. It works on FF but not on IE9.
I tried the onclick function of the commandbutton. It calls the js but submits the form also.
Few code if that helps
JavaScript functions I am using
var validationErrorFound = false;
function validateRequired(element,form){
if(null == element.value || "" == element.value){
var existingClass = element.getAttribute("class");
var newClass = existingClass + " inputError";
element.setAttribute("class", newClass);
var label = document.getElementById(element.getAttribute("id") + "Lbl");
var labelArray = new Array();
var temp = label.innerText;
labelArray = temp.split(":");
element.setAttribute("title", labelArray[0] + " is Required");
validationErrorFound = true;
}else{
element.className = element.className.replace( /(?:^|\s)inputError(?!\S)/ , '' );
element.setAttribute("title", null);
element.removeAttribute("title");
validationErrorFound = false;
}
}
function validateAllRequired(form){
var all = document.getElementsByTagName("input");
var max=all.length;
for (var i=0; i < max; i++) {
if(null != all[i].onblur ){
validateRequired(all[i],form);
}
}
return validationErrorFound;
}
JSF Page
<h:form id="addUserDetailsForm">
<h:messages/>
<h:panelGrid columns="2">
<p:outputLabel id="userNameLbl" for="userName" value="Username:" />
<p:inputText id="userName" required="true" onblur="validateRequired(this,this.form);"
value="#{userList.addUser.userName}">
<f:param name="req" value="true"/>
</p:inputText>
<p:outputPanel value="" />
<p:outputLabel id="firstNameLbl" for="firstName" value="First Name:" />
<p:inputText id="firstName" required="true" onblur="validateRequired(this,this.form);"
value="#{userList.addUser.firstName}"/>
<p:outputLabel id="lastNameLbl" for="lastName" value="Last Name:" />
<p:inputText id="lastName" required="true" onblur="validateRequired(this,this.form);"
value="#{userList.addUser.lastName}"/>
<h:commandButton styleClass="button" value="Add" onclick="validateAllRequired(this.form);"
action="#{userList.dummyAdd}" >
<f:ajax execute="#form" render=":mainArea :propertiesArea" update=":mainArea :propertiesArea"/>
</h:commandButton>
</h:panelGrid>
Is there any way this can be done?
Thanks

Resources