h:commandLink rendered working disabled not working - jsf-2

I have a page on which i am displaying a prime faces table using p dataTable whose value is coming from session scoped bean. One of the columns in table is a commmandLink. I have a h:commandLink under p:columns in the table. I need to render the h:commandLink depending on specific condition. I need to disable / enable the h:commandLink on another condition. The logic written for rendering the h:commandLink works correctly, but logic for disabling it does not work. the h:commandLink has a nested outputText and graphicImage. Even defaulting disabled = "true" does not work. when i click on image displayed for commandLink, i see the dialog which i am displaying using javascript on commandLink onClick.
<p:dataTable value="#{myBean.items}"
id="pdatatableid"
var="oneItem"
rowIndexVar="rowIdxVar"
rows="#{myBean.displayRows}"
cellspacing="0"
width="500px"
emptyMessage="Item(s) requested cannot be found"
lazy="true"
first="#{myBean.firstRow}"
paginator="true"
paginatorPosition="top">
<p:columns value="#{myBean.headerList}" var="colHeader"
columnIndexVar="colIdx" sortBy="#{oneItem[colHeader.attribute]}" headerText="#{colHeader.label}" rendered="#{not empty myBean.headerList}">
<h:commandLink action="#{myBean.performLinkAction(colHeader)}"
rendered="#{colHeader.commandLink && colHeader.linkAction != 'removeWorkItemEscalation' && colHeader.linkAction == 'orderCancellation' && oneItem.cancelOrder}"
disabled="true" immediate="true"
onclick="#{rich:component('cancellationDlg')}.show();return false;">
<h:outputText rendered="#{(colHeader.valueImage) == null}"
value="#{myBean.getColumnValue(colHeader,colIdx)}" />
<h:graphicImage rendered="#{(colHeader.valueImage) != null}"
value="#{colHeader.valueImage}"
alt="#{myBean.getColumnValue(colHeader,colIdx) ? 'Yes':'No'}"
title="Cancel Quote" />
</h:commandLink>
</p:columns>
</p:dataTable>
public boolean getCancelOrder(){
boolean cancelOrder = false;
if(!StringUtils.isEmpty(getOrderVO().getRealm())
&& "NETWORK".equalsIgnoreCase(getOrderVO().getRealm())){
cancelOrder = true;
}
return cancelOrder;
}
above is the bean method used for rendered attribute which is working.
Similar implementation and even defaulting disabled to "true" does not work.

Have a look at the generated HTML. Setting disabled=true will produce a span-Tag.
If the "disabled" attribute is specified, do not render the HTML "a" anchor element or its "href" attribute. Instead, render a "span" element.
https://javaserverfaces.java.net/nonav/docs/2.0/pdldocs/facelets/h/commandLink.html
If there is a attribute onClick, this will produce the client-side behaviour.

I had the same problem and solved by removing the rendered the h: commandLink
and leaving only the h: graphicImage.
<h:commandLink>
<h:graphicImage rendered="#{varDataTable.atribute}"/>
</ h: commandLink>

Using Bootstrap:
I had the same problem and solved it by adding disabled on a EL condition.
<h:commandLink class="#{empty Backing.list?'disabled':''}" action="#{Backing.next}">
<i class="fa fa-calendar"></i>Label
<f:ajax render="#form" />
</h:commandLink>

Using commandButton in place of commandLink solved the problem. while searching for differences between jsf commandButton and commandLink, i found that they generate different kind of HTML elements input and href a respectively and commandLink uses javascript for submit. javascript written on onClick of commandButton is working as expected and is not being invoked when button is disabled. on commandLink javascript was being invoked even if button was disabled.

Related

how to reset form inputs after they are submitted in jsf

so i have this code(not in details)
<p:tabView id="tabviewId">
<p:tab>
<h:form id="mainHeadOfAccountsId_form">
// some input fields with validation
// using viewscoped
<p:commandButton value="Add" process="mainHeadOfAccountsId_form" update="mainHeadOfAccountsId_form :#{p:component('allMainHeadOfAccountsId_table')} :#{p:component('successfullySavedUpdatedId_growl')}" action="#{budgetHeadOfAccountsAction.addMainHeadOfAccountsOnAjax}" />
/// also using <p:datatable id= "allMainHeadOfAccountsId_table" >
</h:form
</p:tab>
<p:tab>
<h:form>
</h:form
</p:tab>
</p:tabView>
<p:growl id="successfullySavedUpdatedId_growl" for="successfullySavedUpdatedFor_growl" value="error" showDetail="false" />
my Question is that when i submit form mainHeadOfAccountsId_form successfully i need to update(reset) all fields which are in mainHeadOfAccountsId_form
but remember that i am also using <h:selectOneMenu> so i want to reset(option[0] selected) not empty, how can i do that ? currently its updating allMainHeadOfAccountsId_table and successfullySavedUpdatedId_growl except mainHeadOfAccountsId_form
i have tired tabviewId:mainHeadOfAccountsId_form but getting exception component not found,
as i am thinking this is just because of #viewScoped and i should reset value of those inputs in my action class (.java), m i right ?
see what primefaces offer for reset input or after submitting the form by the action in the bean reset the values by new or null and recreate the list held by
<h:selectOneMenu>

commandButton doesn't set correctly f:param if it got a javascript method in onclick event

Between two JSF views xhtmls (both have view scoped backing beans) I would like to pass parameters if the user click a link or a button. If I have an attribute onclick with a JavaScript function to open another page (in this page I would like to use the parameters set in the first page) to the commandButton or commandLink I get the f:param attributes to be \'currentAccess\':\'3\',\'gridNo\':\'5\', and if I don't have an onclick attribute I have it right 'currentAccess':'3','gridNo':'5',
If I have:
<h:commandButton action="#{statisticsBean.showAccessIncorectAnswers()}" target="_blank"
value="#{strings.whatHaveDoDoneWrong}" rendered="#{o.date != '-' and o.answerNoWrong != 0}">
<f:param name="currentAccess" value="#{o.currentAccess}"/>
<f:param name="gridNo" value="#{o.noGrid}"/>
<f:param name="gridCategory" value="#{o.category}"/>
</h:commandButton>
the HTML rendering looks like:
<input type="submit" name="j_idt73:0:j_idt74:j_idt77" value="Ce ai gresit" onclick="mojarra.jsfcljs(document.getElementById('j_idt73:0:j_idt74'),{'j_idt73:0:j_idt74:j_idt77':'j_idt73:0:j_idt74:j_idt77','currentAccess':'1','gridNo':'5','gridCategory':'Drept Procesual Civil'},'');return false" />
which is good, I have access to the parameters (f:viewpara or FacesContext , I use the last one likeFacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("currentAccess"))
BUT
If I have:
<h:commandButton action="#{statisticsBean.showAccessIncorectAnswers()}" target="_blank"
onclick="confirmGridStatistics('#{strings.doYouWantToSeeTheWrongAnswersInAccessNo} #{o.currentAccess} #{strings.fromDate} #{o.date}?');"
value="#{strings.whatHaveDoDoneWrong}" rendered="#{o.date != '-' and o.answerNoWrong != 0}">
<f:param name="currentAccess" value="#{o.currentAccess}"/>
<f:param name="gridNo" value="#{o.noGrid}"/>
<f:param name="gridCategory" value="#{o.category}"/>
</h:commandButton>
WITH a JavaScript function in onclick event I get the rendering:
<input type="submit" name="j_idt73:2:j_idt74:j_idt77" value="Ce ai gresit" onclick="jsf.util.chain(this,event,'confirmGridStatistics(\'Vrei sa vezi raspunsurile gresite in accessul 3 din data de 16-05-2013?\');','mojarra.jsfcljs(document.getElementById(\'j_idt73:2:j_idt74\'),{\'j_idt73:2:j_idt74:j_idt77\':\'j_idt73:2:j_idt74:j_idt77\',\'currentAccess\':\'3\',\'gridNo\':\'5\',\'gridCategory\':\'Drept Procesual Civil\'},\'\')');return false" />
and in the second views backing bean I get null for the parameters from the FacesContext. Why is that?
UPDATE
I thought that
FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().put("currentAccess", access); in the action method whould solve it. But it doesn't, it gives me a java.lang.UnsupportedOperationException
I don't know why this is happening.
I have resolved the my issue with a hack. I still don't know why is the issue described with the parameters.
My solution (I know it`s a hack):
the JavaScipt function among other thing opened my second view (to which I wanted to pass the parameters)
so I have put the parameters (which I want to pass) to the JavaScipt function
<h:commandButton action="#{statisticsBean.showAccessIncorectAnswers()}" target="_blank"
onclick="confirmGridStatistics('#{strings.doYouWantToSeeTheWrongAnswersInAccessNo} #{o.currentAccess} #{strings.fromDate} #{o.date}?'
, '#{o.currentAccess}', '#{o.noGrid}', '#{o.category}');"
value="#{strings.whatHaveDoDoneWrong}" rendered="#{o.date != '-' and o.answerNoWrong != 0}"/>
and the second view request URL looks like http://myserver:port/access.xhtml?currentAccess=34&noGrid=3&category=category
and in the second view backing bean I access the parameters with
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
String currentAccess= request.getParameter("currentAccess");
STILL
If anybody knows why is the initial issue that I would appreciate it to share.
Thank you.

Primefaces inputtext focus at the end of the text

Here a snippet of my JSF:
<p:tabView id="tabView" var="tab" value="#{data.tabs}" widgetVar="tabViewWidget"
activeIndex="#{data.newActiveTabIndex}">
<p:ajax event="tabClose" listener="#{logic.closeTab}" />
<p:tab title="#{tab.content.title != null ? tab.content.title : '&lt;new&gt;'}"
closable="#{tab.isClosable and data.tabs.size() > 2}">
<h:outputText value="#{tab.id} Test" />
<p:focus rendered="#{data.componentIdToFocus != null}" for="#{data.componentIdToFocus}" />
<p:inputText id="test" value="#{tab.content.title}">
<p:ajax event="keyup" listener="#{logic.setFocusingComponent}" update=":form:tabView" />
</p:inputText>
</p:tab>
</p:tabView>
The intent is that there is a textfield within each tab that updates the title of the tab while writing.
The given snippet works except that p:focus places the cursor at the beginning of the text that is already written. I want the cursor to be placed at the end of the text already written. So that a user can type and while he/she is typing the title adapts automatically.
I hope my case is clear.
Does anybody have a solution for that?
Best regards,
Florian
You can use the onfocus="this.value=this.value" trick to "deselect" the value so that the cursor automagically ends up in the end of the value. This should work as good for the <p:inputText> as it basically generates just a <input type="text"> element.
<p:inputText ... onfocus="this.value=this.value" />
See also:
Use JavaScript to place cursor at end of text in text input element
Unrelated to the concrete problem, I wouldn't use ajax and such on keyup event and an update of the whole tabview. This seems to be quite expensive. I'd rather do a simple HTML DOM traversion and manipulation here by JS/jQuery.
E.g.
<p:inputText ... onkeyup="updateTitle(this)" />
with
function updateTitle(inputInTab) {
var panelId = $(inputInTab).closest(".ui-tabs-panel").attr("id");
$("a[href='#" + panelId + "']").text(inputInTab.value);
}

How to find indication of a Validation error (required="true") while doing ajax command

I have a form inside a dialog which I close by clicking on commandbutton with ajax ,
like this
<h:commandButton value="Add" action="#{myBean.addSomething(false)}"
id="add_something_id" >
<f:ajax render="#form someTable" execute="#form"
onevent="closeAddNewSomethingDialogIfSucceeded"></f:ajax>
</h:commandButton>
and here is the js code for closing the dialog
function closeAddNewSomethingDialogIfSucceeded(data) {
if(data.status === 'success') {
$("#dialog_id").dialog("close");
}
}
No problems till here...
Now I changed some of the dialog form fields into required="true" and now I want to prevent the closing of the dialog of i got validation errors...
But the ajax data.status still reaches its success state , and I can't figure out what indication of validation failure I can hook on...
any ideas?
Thanks to BalusC answer I did the following:
in JSF , added :
<h:panelGroup id="global_flag_validation_failed_render">
<h:outputText id="global_flag_validation_failed" value="true"
rendered="#{facesContext.validationFailed}"/>
</h:panelGroup>
the f:ajax was changed into
<f:ajax render="#form someTable global_flag_validation_failed_render"
and in js added the following check
if(data.status === 'success') {
if($("#global_flag_validation_failed").length === 0){
$("#dialog_id").dialog("close");
}
}
Not specifically for required="true", but you can check by #{facesContext.validationFailed} if validation has failed in general. If you combine this with checking if the button in question is pressed by #{not empty param[buttonClientId]}, then you can put it together in the rendered attribute of the <h:outputScript> as follows:
<h:commandButton id="add_something_id" binding="#{add}" value="Add" action="#{myBean.addSomething(false)}">
<f:ajax execute="#form" render="#form someTable" />
</h:commandButton>
<h:outputScript rendered="#{not empty param[add.clientId] and not facesContext.validationFailed}">
$("#dialog_id").dialog("close");
</h:outputScript>
(note that you need to make sure that the script is also re-rendered by f:ajax)
A bit hacky, but it's not possible to handle it in the onevent function as the standard JSF implementation doesn't provide any information about the validation status in the ajax response.
If you happen to use RichFaces, then you could just use EL in the oncomplete attribute of the <a4j:xxx> command button/link. They are namely evaluated on a per-request basis instead of on a per-view basis as in standard JSF and PrimeFaces:
<a4j:commandButton ... oncomplete="if (#{!facesContext.validationFailed}) $('#dialog_id').dialog('close')" />
Or if you happen to use PrimeFaces, then you could take advantage of the fact that PrimeFaces extends the ajax response with an additional args.validationFailed attribute which is injected straight in the JavaScript scope of the oncomplete attribute:
<p:commandButton ... oncomplete="if (args && !args.validationFailed) $('#dialog_id').dialog('close')" />
(note that & is been used instead of &, because & is a special character in XML/XHTML)
Or you could use the PrimeFaces' RequestContext API in the bean's action method to programmatically execute JavaScript in the rendered view.
RequestContext.getCurrentInstance().execute("$('#dialog_id').dialog('close')");
No conditional checks are necessary as the bean's action method won't be invoked anyway when the validation has failed.
Two things
1) Checking for an error in the 'onevent' function
Surely you have a message tag for the mandatory field?
<h:message id="m-my-field-id" for="my-field-id" errorClass="error-class"/>
So you can check for the error-class something like
var message = $('#m-my-field-id');
if(message.hasClass('error-class'){
//do this
}
else{
//do that
}
2) The DOM isn't up to date on success
Yes, I can see the message on the page in Firefox, yet jQuery tells me it is not there.
I have found that using the smallest possible timeout is sufficient to fix this
setTimeout(
function(){
setErrorStyle(source.attr('id'));
},
1
);
I think you should take a look at PrimeFaces' RequestContext. This would help you trigger client-side code on the server side.
#BalusC
in your example code the clientId of the button is not set as a param because it is a AJAX request. So
not empty param[add.clientId] is always false.
But this works:
param['javax.faces.source'] eq add.clientId
(tested with jsf-impl-2.2.12.redhat-1)
regards

Why does my s:selectItems throws no such element exception?

I'm getting this error java.util.NoSuchElementException when i tried to check one of my checkbox under h:selectManycheckBox when i submit the form.
The many checkbox is dynamically populated from the bean. Here is my code.
<h:form id="eF">
<h:inputText id="i" value="#{aklat.suggest}">
<a4j:support event="onkeyup" action="#{aklat.complete}" reRender="m"></a4j:support>
</h:inputText>
<s:div>
<h:selectManyCheckbox value="#{aklat.selectedBooks}" layout="pageDirection" id="m">
<s:selectItems value="#{aklat.books}" var="_book" itemLabel="#{_book}" itemValue="#{_book}" label="#{_book.bookName}"/>
</h:selectManyCheckbox>
<a4j:commandButton value="Add Users" action="#{aklat.fire}"></a4j:commandButton>
</s:div>
</h:form>
The weird part is it renders some data output but when i checked the source code. there are no input type checkbox element.
Is something I am missing.
I assume your managed bean is request scope...
because you are making an ajax request, you have to enable "aklat.books" to persist its value longer than request but shorther than session scope.
If you have tomahawk between your app libraries you can use savestate like this (put it after the h:form tag) :
<t:saveState value="#{aklat.books}"/>
if no tomahawk, you can use a4j:keepAlive:
<a4j:keepAlive beanName = "#{aklat.books}"/>

Resources