I need to click the button twice to make the calculation - jsf

I have a method that calculates a charge but you need to click the button twice for it to calculate
This is the method that fetches the data in the database and calculates
public Float findTarifaBandeira1() {
try {
//SQL
} catch (NoResultException ne) {
System.out.print("Tarifa não encontrada"); // Colocar messagesfaces
}
tarifaBand1 = (bandeira.getValorInicial() + ( bandeira.getTarifaCorrida().getValorKm() * km));
BigDecimal vt = new BigDecimal(tarifaBand1).setScale(2, RoundingMode.HALF_EVEN);
tarifaBand1 = vt.floatValue();
return tarifaBand1;
}
This method fires the click of the button calls other methods and the method above
I have a method that calculates a charge but you need to click the button twice for it to calculate
public void consultarBandeira() throws ParseException {
getData();
getHora();
convertDistance();
findTarifaBandeira1();
findTarifaBandeira2();
findTarifaVolumesDeMao ();
findTarifaVolumesNormais ();
findTarifaVolumesGrandes();
}
In my JSF page I use a remote command to call the above method
<p:commandButton value="#{msg['btn-search']}"
styleClass="btn btn-primary" onclick="findRoute()"/>
<p:remoteCommand actionListener="#{searchBean.consultarBandeira()}"
id="consultaValor" name="consultaValor"
update="bandeira1, bandeira2, nomeVPequenos,
descricaoVPequenos, valorVpequenos, nomeVNormais,
descricaoVNormais, valorVNormais, nomeVGrandes,
descricaoVGrandes, valorVGrandes"/>
findRoute() is a function that calls the JavaScript consultaValor component that triggers the method in my searchBean.
function findRoute(){
event.preventDefault();
var addressOrigin = origin;
var addressDestination = document.getElementById("addr").value +
document.getElementById("city").value;
var request = {
origin: addressOrigin,
destination: addressDestination,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.metric
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
directionsDisplay.setPanel(document.getElementById("route"));
var route = response.routes[0];
for (var i = 0; i < route.legs.length; i++){
routeSegment = i + 1;
distance = route.legs[i].distance.value;
}
document.getElementById("distance").value = distance;
}
});
consultaValor();
}

When you click the commandButton, it does a postback to the server twice: once for the remoteCommand and once for the button itself. This is most likely the cause of your problem.
Since you're essentially using the button for client-side action only, instruct your commandButton to not postback via onclick.
Also, since you're setting form data in the findRoute() javascript method, you'll need to make sure it is processed on the backend. The default value of process for remoteCommand is #this.
<p:commandButton value="#{msg['btn-search']}"
styleClass="btn btn-primary" onclick="findRoute(); return false"/>
<p:remoteCommand actionListener="#{searchBean.consultarBandeira()}"
id="consultaValor" name="consultaValor"
process="#form"
update="bandeira1, bandeira2, nomeVPequenos,
descricaoVPequenos, valorVpequenos, nomeVNormais,
descricaoVNormais, valorVNormais, nomeVGrandes,
descricaoVGrandes, valorVGrandes"/>
But if it were me, I'd simplify this by combining the logic into the commandbutton itself:
<p:commandButton value="#{msg['btn-search']}"
styleClass="btn btn-primary" onstart="findRoute()"
action="#{searchBean.consultarBandeira()}"
process="#form"
update="bandeira1, bandeira2, nomeVPequenos,
descricaoVPequenos, valorVpequenos, nomeVNormais,
descricaoVNormais, valorVNormais, nomeVGrandes,
descricaoVGrandes, valorVGrandes" />

Related

Primefaces CommandButton disable and enable

<p:commandButton id .......
onclick=”disableButton(this);”
onkeypress=”disableButton(this);”
oncomplete="enableButton('${bean.enableButton()}');"
private boolean enableButton(){
return false;
}
<script>
function disableButton(data) {
data.disable = true;
}
function enableButton(data) {
data.disable = data;
}
</script>
Observed both calls working in the debugger, but the button remains disabled
When disableButton is called data = button#MessageView j_idt183:….
When enableButton is called data = {url: “ ……….}
from the debugger
<p:commandButton id .......
onclick=”disableButton(this);”
onkeypress=”disableButton(this);”
oncomplete="enableButton();"
<script>
function disableButton(data) {
data.disable = true;
window.buttonPressed.disabled = data
}
// Save and use the initial "data" object
function enableButton() {
window.buttonPressed.disabled = false;
}

Popup exceptions in line items (SOLine)

How to display popup exceptions instead of the one with a red dot on the row for the line items? I was able to have them in RowInserting for a little bit but after a series of code changes I get the red dot one instead. It even did not create a new row as I wanted but now it does. RowInserting event:
protected virtual void SOLine_RowInserting(PXCache sender, PXRowInsertingEventArgs e)
{
var listMissingOEdesc = new List<int>();
var select = Base.Transactions.Select();
foreach (SOLine row in select)
{
var isOEDesc = IsOEDescEnabled(sender, row);
var rowExt = PXCache<SOLine>.GetExtension<SOLineExt>(row);
if (isOEDesc == true)
if (rowExt.UsrOedesc == null)
listMissingOEdesc.Add(row.SortOrder.Value);
}
if (listMissingOEdesc.Count > 0)
{
throw new PXException("Line items with sort order {0} do not have OE Desc filled out. Cannot add a new line.", string.Join(", ", listMissingOEdesc));
}
else
Base.Actions.PressSave();
}
Thanks!
There is no easy way, if any at all, to display popup exception and prevent the grid from inserting a new row. The way the framework is designed, PXGrid first inserts a new row on the webpage. After that PXGrid sends a callback to the application server either requesting default field values for the new row (if PXGrid's Mode has InitNewRow="True") or sends all values captured from the webpage to the application server, so the new row can be inserted in the PXCache. Whenever an event handler, on the field or row level, gets invoked, the new row will still be visible to the user on the web page. Even if you invoke Ask method on the Transactions data view within one of the event handlers, the new row won't disappear from the webpage.
With all that said, the best and probably the only way to display popup exception and prevent the grid from inserting a new row is by replacing the standard Add New Row button on PXGrid with a custom action, which will first run the validation and display popup exception, if necessary. Otherwise, a new row will be inserted into PXGrid. It's also required to enable or disable the custom NewSOTran action based on the state of the standard PXGrid's Insert button.
public class SOOrderEntryExt : PXGraphExtension<SOOrderEntry>
{
public void SOOrder_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
{
NewSOTran.SetEnabled(Base.Transactions.AllowInsert);
}
public PXAction<SOOrder> NewSOTran;
[PXButton(CommitChanges = true)]
[PXUIField]
protected void newSOTran()
{
var listMissingOEdesc = new List<SOLine>();
var select = Base.Transactions.Select();
foreach (SOLine row in select)
{
var isOEDesc = !string.IsNullOrEmpty(row.TranDesc);
if (isOEDesc == true)
listMissingOEdesc.Add(row);
}
if (listMissingOEdesc.Count > 0)
{
throw new PXException("Cannot add a new line.");
}
var newTran = Base.Transactions.Insert();
Base.Transactions.Cache.ActiveRow = newTran;
}
}
In Aspx there will required 3 major chages:
SyncPositionWithGraph property set to True for PXGrid:
<px:PXGrid ID="grid" runat="server" DataSourceID="ds" Width="100%" TabIndex="100"
SkinID="DetailsInTab" StatusField="Availability" SyncPosition="True" Height="473px"
SyncPositionWithGraph="True" >
the standard AddNew action must be replaced by a custom NewSOTran action:
<ActionBar>
<Actions>
<AddNew ToolBarVisible ="False" />
</Actions>
<CustomItems>
<px:PXToolBarButton CommandName="NewSOTran" CommandSourceID="ds"
DisplayStyle="Image">
<Images Normal="main#AddNew" />
<ActionBar GroupIndex="0" Order="2" />
</px:PXToolBarButton>
...
</CustomItems>
</ActionBar>
AllowAddNew property set to false in the Mode section of PXGrid to prevent the standart Insert button from execution when users use keyboard shortcuts or double-click on PXGrid:
<Mode InitNewRow = "True" AllowFormEdit="True" AllowUpload="True" AllowDragRows="true"
AllowAddNew="false" />
To select new records’ first cell and switch it to the edit mode (unless the first cell is read-only), it's also required to subscribe to the Initialize and ToolsButtonClick client events of PXGrid:
<ClientEvents Initialize="initTransactionsGrid"
ToolsButtonClick="transactionsGriduttonClick" />
and define the following JavaScript functions:
var isInitEvents = false;
function initTransactionsGrid(a, b) {
if (isInitEvents) return;
isInitEvents = true;
a.events.addEventHandler("afterRepaint", editNewSOTran);
}
function editNewSOTran() {
if (lastActiveRowIndex != null) {
var grid = px_alls["grid"];
if (grid.activeRow) {
var activeRowIndex = grid.rows.indexOf(grid.activeRow);
if (activeRowIndex != lastActiveRowIndex) {
grid.activeRow.activateCell(0, false);
grid.beginEdit();
}
}
lastActiveRowIndex = null;
}
}
var lastActiveRowIndex;
function transactionsGriduttonClick(sender, args) {
if (args.button && args.button.commandName == "NewSOTran") {
if (sender.activeRow)
lastActiveRowIndex = sender.rows.indexOf(sender.activeRow);
else
lastActiveRowIndex = -1;
return;
}
lastActiveRowIndex = null;
}
To package custom JavaScript code into customization, in Layout Editor you can drag and drop a Java Script element from the Add Controls tab and copy your entire JavaScript code into the Script property.

Primefaces Draggable Drop Position

I need to get the drop position of a draggable panel. But i cannot figure out how to do it. I've tried to get the style but I've got unrelated information.
Here is my xhtml :
<h:form id="dnd">
<p:panel id="draggable1"
style="z-index:1; width: 60px; height: 60px;">
<h:outputText value="CAM-1" />
<p:draggable for="draggable1"
revert ="false"/>
</p:panel>
<p:panel id="droppable"
style="z-index:1; width: 600px; height: 600px;">
<p:droppable for="droppable">
<p:ajax listener="#{myBean.onDrop}" />
</p:droppable>
</p:panel>
</h:form>
Here is my backing bean :
public void onDrop(DragDropEvent dragDropEvent) {
String dragId = dragDropEvent.getDragId();
UIComponent draggedItem = FacesContext.getCurrentInstance().getViewRoot().findComponent(dragId);
System.out.println(draggedItem.getClientId());
Panel draggedPanel = (Panel) draggedItem;
String style = draggedPanel.getStyle();
System.out.println(style);
String styleClass = draggedPanel.getStyleClass();
System.out.println(styleClass);
}
Any help will be appreciated. Thanks in advance.
PrimeFaces is using jQuery UI .droppable(), to get the position you should alter the event binding in PrimeFaces.widget.Droppable, this is done in bindDropListener.
Adding a couple of request params to the original request would do it, here's an example:
PrimeFaces.widget.Droppable.prototype.bindDropListener = function() {
var _self = this;
this.cfg.drop = function(event, ui) {
if (_self.cfg.onDrop) {
_self.cfg.onDrop.call(_self, event, ui);
}
if (_self.cfg.behaviors) {
var dropBehavior = _self.cfg.behaviors['drop'];
if (dropBehavior) {
var ext = {
params: [
{name: _self.id + '_dragId', value: ui.draggable.attr('id')},
{name: _self.id + '_dropId', value: _self.cfg.target},
{name: ui.draggable.attr('id') + '_left', value: ui.position.left},
{name: ui.draggable.attr('id') + '_top', value: ui.position.top}
]
};
dropBehavior.call(_self, ext);
}
}
};
}
The change here is adding two more parameters to the ext params of the request, where the positions of the draggable item (left, top) are present.
On the other side of the event onDrop(DragDropEvent dragDropEvent), you can find them as request parameters as I have mentioned.
public void onDrop(DragDropEvent dragDropEvent) {
String dargId = dragDropEvent.getDragId();
Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String left = params.get(dargId + "_left");
String top = params.get(dargId + "_top");
}
Note: the ajax event should be present in p:droppable (as in the question)
You can find a small example on github, and a working demo.

h:commandButton/h:commandLink does not work on first click, works only on second click

We have an ajax navigation menu which updates a dynamic include. The include files have each their own forms.
<h:form>
<h:commandButton value="Add" action="#{navigator.setUrl('AddUser')}">
<f:ajax render=":propertiesArea" />
</h:commandButton>
</h:form>
<h:panelGroup id="propertiesArea" layout="block">
<ui:include src="#{navigator.selectedLevel.url}" />
</h:panelGroup>
It works correctly, but any command button in the include file doesn't work on first click. It works only on second click and forth.
I found this question commandButton/commandLink/ajax action/listener method not invoked or input value not updated and my problem is described in point 9.
I understand that I need to explicitly include the ID of the <h:form> in the include in the <f:ajax render> to solve it.
<f:ajax render=":propertiesArea :propertiesArea:someFormId" />
In my case, however, the form ID is not known beforehand. Also this form will not be available in the context initally.
Is there any solution to the above scenario?
You can use the following script to fix the Mojarra 2.0/2.1/2.2 bug (note: this doesn't manifest in MyFaces). This script will create the javax.faces.ViewState hidden field for forms which did not retrieve any view state after ajax update.
jsf.ajax.addOnEvent(function(data) {
if (data.status == "success") {
fixViewState(data.responseXML);
}
});
function fixViewState(responseXML) {
var viewState = getViewState(responseXML);
if (viewState) {
for (var i = 0; i < document.forms.length; i++) {
var form = document.forms[i];
if (form.method == "post") {
if (!hasViewState(form)) {
createViewState(form, viewState);
}
}
else { // PrimeFaces also adds them to GET forms!
removeViewState(form);
}
}
}
}
function getViewState(responseXML) {
var updates = responseXML.getElementsByTagName("update");
for (var i = 0; i < updates.length; i++) {
var update = updates[i];
if (update.getAttribute("id").match(/^([\w]+:)?javax\.faces\.ViewState(:[0-9]+)?$/)) {
return update.textContent || update.innerText;
}
}
return null;
}
function hasViewState(form) {
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].name == "javax.faces.ViewState") {
return true;
}
}
return false;
}
function createViewState(form, viewState) {
var hidden;
try {
hidden = document.createElement("<input name='javax.faces.ViewState'>"); // IE6-8.
} catch(e) {
hidden = document.createElement("input");
hidden.setAttribute("name", "javax.faces.ViewState");
}
hidden.setAttribute("type", "hidden");
hidden.setAttribute("value", viewState);
hidden.setAttribute("autocomplete", "off");
form.appendChild(hidden);
}
function removeViewState(form) {
for (var i = 0; i < form.elements.length; i++) {
var element = form.elements[i];
if (element.name == "javax.faces.ViewState") {
element.parentNode.removeChild(element);
}
}
}
Just include it as <h:outputScript name="some.js" target="head"> inside the <h:body> of the error page. If you can't guarantee that the page in question uses JSF <f:ajax>, which would trigger auto-inclusion of jsf.js, then you might want to add an additional if (typeof jsf !== 'undefined') check before jsf.ajax.addOnEvent() call, or to explicitly include it by
<h:outputScript library="javax.faces" name="jsf.js" target="head" />
Note that jsf.ajax.addOnEvent only covers standard JSF <f:ajax> and not e.g. PrimeFaces <p:ajax> or <p:commandXxx> as they use under the covers jQuery for the job. To cover PrimeFaces ajax requests as well, add the following:
$(document).ajaxComplete(function(event, xhr, options) {
if (typeof xhr.responseXML != 'undefined') { // It's undefined when plain $.ajax(), $.get(), etc is used instead of PrimeFaces ajax.
fixViewState(xhr.responseXML);
}
}
Update if you're using JSF utility library OmniFaces, it's good to know that the above has since 1.7 become part of OmniFaces. It's just a matter of declaring the following script in the <h:body>. See also the showcase.
<h:body>
<h:outputScript library="omnifaces" name="fixviewstate.js" target="head" />
...
</h:body>
Thanks to BalusC since his answer is really great (as usual :) ). But I have to add that this approach does not work for ajax requests coming from RichFaces 4. They have several issues with ajax and one of them is that the JSF-ajax-handlers are not being invoked. Thus, when doing a rerender on some container holding a form using RichFaces-components, the fixViewState-function is not called and the ViewState is missing then.
In the RichFaces Component Reference, they state how to register callbacks for "their" ajax-requests (in fact they're utilizing jQuery to hook on all ajax-requests).
But using this, I was not able to get the ajax-response which is used by BalusC's script above to get the ViewState.
So based on BalusC's fix, i worked out a very similar one. My script saves all ViewState-values of all forms on the current page in a map before the ajax-request is being processed by the browser. After the update of the DOM, I try to restore all ViewStates which have been saved before (for all forms which are missing the ViewState now).
Move on:
jQuery(document).ready(function() {
jQuery(document).on("ajaxbeforedomupdate", function(args) {
// the callback will be triggered for each received JSF AJAX for the current page
// store the current view-states of all forms in a map
storeViewStates(args.currentTarget.forms);
});
jQuery(document).on("ajaxcomplete", function(args) {
// the callback will be triggered for each completed JSF AJAX for the current page
// restore all view-states of all forms which do not have one
restoreViewStates(args.currentTarget.forms);
});
});
var storedFormViewStates = {};
function storeViewStates(forms) {
storedFormViewStates = {};
for (var formIndex = 0; formIndex < forms.length; formIndex++) {
var form = forms[formIndex];
var formId = form.getAttribute("id");
for (var formChildIndex = 0; formChildIndex < form.children.length; formChildIndex++) {
var formChild = form.children[formChildIndex];
if ((formChild.hasAttribute("name")) && (formChild.getAttribute("name").match(/^([\w]+:)?javax\.faces\.ViewState(:[0-9]+)?$/))) {
storedFormViewStates[formId] = formChild.value;
break;
}
}
}
}
function restoreViewStates(forms) {
for (var formIndexd = 0; formIndexd < forms.length; formIndexd++) {
var form = forms[formIndexd];
var formId = form.getAttribute("id");
var viewStateFound = false;
for (var formChildIndex = 0; formChildIndex < form.children.length; formChildIndex++) {
var formChild = form.children[formChildIndex];
if ((formChild.hasAttribute("name")) && (formChild.getAttribute("name").match(/^([\w]+:)?javax\.faces\.ViewState(:[0-9]+)?$/))) {
viewStateFound = true;
break;
}
}
if ((!viewStateFound) && (storedFormViewStates.hasOwnProperty(formId))) {
createViewState(form, storedFormViewStates[formId]);
}
}
}
function createViewState(form, viewState) {
var hidden;
try {
hidden = document.createElement("<input name='javax.faces.ViewState'>"); // IE6-8.
} catch(e) {
hidden = document.createElement("input");
hidden.setAttribute("name", "javax.faces.ViewState");
}
hidden.setAttribute("type", "hidden");
hidden.setAttribute("value", viewState);
hidden.setAttribute("autocomplete", "off");
form.appendChild(hidden);
}
Since I am not an JavaScript-expert, I guess that this may be improved further. But it definitely works on FF 17, Chromium 24, Chrome 12 and IE 11.
Two additional questions to this approach:
Is it feasible to use the same ViewState-value again? I.e. is JSF assigning the same ViewState-value to each form for every request/response? My approach is based on this assumption (and I have not found any related information).
Does someone expect any problems with this JavaScript-code or already ran into some using any browser?

Sharepoint InputFormTextBox not working on updatepanel?

I have two panels in update panel. In panel1, there is button. If I click, Panel1 will be visible =false and Panel2 will be visible=true. In Panel2, I placed SharePoint:InPutFormTextBox. It not rendering HTML toolbar and showing like below image.
<SharePoint:InputFormTextBox runat="server" ID="txtSummary" ValidationGroup="CreateCase" Rows="8" Columns="80" RichText="true" RichTextMode="Compatible" AllowHyperlink="true" TextMode="MultiLine" />
http://i700.photobucket.com/albums/ww5/vsrikanth/careersummary-1.jpg
SharePoint rich text fields start out as text areas, and some javascript in the page load event replaces them with a different control if you are using a supported browser.
With an update panel, the page isn't being loaded, so that script never gets called.
Try hiding the section using css/javascript rather than the server side visible property. That generally lets you make whatever changes you need to the form without sharepoint seeing any changes.
<SharePoint:InputFormTextBox ID="tbComment" CssClass="sp-comment-textarea" runat="server" TextMode="MultiLine" RichText="True"></SharePoint:InputFormTextBox>
<%--textbox for temporay focus - trick the IE behavior on partial submit--%>
<input type="text" id="<%= tbComment.ClientID %>_hiddenFocusInput_" style="width: 0px; height: 0px; position: absolute; top: -3000px;" />
<%--tricking code that makes the 'SharePoint:InputFormTextBox' to work correctly in udate panel on partial podtback--%>
<script id="<%= tbComment.ClientID %>_InputFormTextBoxAfterScript" type="text/javascript">
(function () {
// where possible rich textbox only
if (browseris.ie5up && (browseris.win32 || browseris.win64bit) && !IsAccessibilityFeatureEnabled()) {
// find this script element
var me = document.getElementById("<%= tbComment.ClientID %>_InputFormTextBoxAfterScript");
if (me) {
// search for script block of the rich textbox initialization
var scriptElement = me.previousSibling;
while (scriptElement && (scriptElement.nodeType != 1 || scriptElement.tagName.toLowerCase() != "script")) {
scriptElement = scriptElement.previousSibling;
}
// get the content of the found script block
var innerContent = scriptElement.text;
if (typeof innerContent == 'undefined') {
innerContent = scriptElement.innerHTML
}
// get text with function call that initializes the rich textbox
var callInitString = "";
innerContent.toString().replace(/(RTE_ConvertTextAreaToRichEdit\([^\)]+\))/ig, function (p0, p1) { callInitString = p1; });
// register on page load (partial updates also)
Sys.Application.add_load(function (sender, args) {
setTimeout(function () {
// get the toolbar of the rich textbox
var toolbar = $get("<%= tbComment.ClientID %>_toolbar");
// if not found then we should run initialization
if (!toolbar) {
// move focus to the hidden input
$get("<%= tbComment.ClientID %>_hiddenFocusInput_").focus();
// reset some global variables of the SharePoint rich textbox
window.g_aToolBarButtons = null;
window.g_fRTEFirstTimeGenerateCalled = true;
window.g_oExtendedRichTextSupport = null;
parent.g_oExtendedRichTextSupport = null;
// call the initialization code
eval(callInitString);
setTimeout(function () {
// call 'onload' code of the rich textbox
eval("RTE_TextAreaWindow_OnLoad('<%= tbComment.ClientID %>');");
}, 0);
}
}, 0);
});
}
}
})();
</script>

Resources