Primefaces CommandButton disable and enable - jsf

<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;
}

Related

Add tab to the tabpanel on mvc

I have a menu and some menu items.when I clcik to menu item I create new panle codebehind and add it to main tabpanel.so far so good ,but it seems for every click on the menu,panel created from the begining,plus,change place of the the tabs.how can I solve this.
here is the my Index.cshtml
<body>
#Html.X().ResourceManager()
#(
Html.X().Viewport()
.Layout(LayoutType.Border)
.Items(
Html.X().Panel()
.Region(Region.West)
.Title("main menu")
.Width(200)
.Collapsible(true)
.Split(true)
.MinWidth(175)
.MaxWidth(400)
.MarginSpec("5 0 5 5")
.Layout(LayoutType.Accordion)
.Items(
Html.X().MenuPanel()
.Collapsed(true)
.Icon(Icon.Note)
.AutoScroll(true)
.Title("menu")
.ID("PNL34")
.BodyPadding(0)
.Menu(menu => {
menu.Items.Add(Html.X().MenuItem().ID("1a").Text("test1").Icon(Icon.Anchor)
.DirectEvents(m => { m.Click.Url = "Desktop/AddTab";
m.Click.ExtraParams.Add(new { conid = "TabPanel1" ,pnlid="tabpnl10",viewname="Urunler"});
}));
menu.Items.Add(Html.X().MenuItem().ID("2a").Text("test2").Icon(Icon.Anchor)
.DirectEvents(m =>
{
m.Click.Url = "Desktop/AddTab";
m.Click.ExtraParams.Add(new { conid = "TabPanel1", pnlid = "tabpnl11", viewname = "Siparisler" });
}));
})
)
,
Html.X().TabPanel()
.ID("TabPanel1")
.Region(Region.Center)
.Title("E-TICARET")
.MarginSpec("5 5 5 0")
))
and codebehind controller
public ActionResult AddTab(string conid,string pnlid,string viewname)
{
var cmp = this.GetCmp<Panel>(pnlid);
var cmp2 = this.GetCmp<TabPanel>(conid);
if (cmp.ActiveIndex==-1)
{
var result = new Ext.Net.MVC.PartialViewResult
{
ViewName = viewname,
ContainerId = conid,
RenderMode = RenderMode.AddTo,
WrapByScriptTag = false
};
cmp2.SetActiveTab(pnlid);
return result;
}
else
{
return null;
}
}
This is not going to work.
if (cmp.ActiveIndex == -1)
In WebForms it is retrieved from the Post data. There is no a WebForms-like Post in MVC. You should send all the required information with a request.
Also if you don't need a tab to be rendered if it is already exists, just stop a request. You can determine on client if a tab is already there or not.

primefaces remoteCommand action is not getting called

I have the following code:
<p:remoteCommand name="navigateTo" actionListener="#{searchControllerHelper.dummyActionListener}"
action="#{searchControllerHelper.navigateTo}" update="searchPanelForm"
onstart="plsWaitDlg.show()" onsuccess="plsWaitDlg.hide()"/>
Controller Code as under:
Thank you Lars. Code of the bean as under:
public String navigateTo() throws FetchException {
if (null == this.getSelectedMenuLink()) {
return null;
}
if (this.getSelectedMenuLink().longValue() == 1L) {
this.prevSelectedMenuLink = this.selectedMenuLink;
this.location = null;
return searchCRE();
}
else if (this.getSelectedMenuLink().longValue() == 2L) {
this.prevSelectedMenuLink = this.selectedMenuLink;
this.selectedLoanType=null;
return searchLoans();
}
else if (this.getSelectedMenuLink().longValue() == 3L) {
this.prevSelectedMenuLink = this.selectedMenuLink;
this.selectedLoanType=null;
return searchLoans();
}
else if (this.getSelectedMenuLink().longValue() == 4L) {
this.prevSelectedMenuLink = this.selectedMenuLink;
return otherOpportunities();
}
else if (this.getSelectedMenuLink().longValue() == 5L) {
//The link needs to be 'activated' once a service provider is selected.
this.prevSelectedMenuLink= this.selectedMenuLink;
return this.navigateToHome();
}
return null;
}
I added the actionlistener to check if the controller was getting fired or not, and it is.
What is happening is the following: The page loads, and before it is completely done loading if the user clicks the button that calls this remoteCommand then strangely the actionListener gets called, but the action method does not.
Any ideas what I could do to alleviate this issue?
Thank you
Karthik

Ajax.OnBeginForm(... OnSuccess = "xxx") always fires after initial success

I am using VS2012 / C# / MVC 4.
I am trying to Post a "Contact Us" form without refreshing the whole page. All is fine, the validation kicks in the first time if I miss any required fields and OnSuccess is not fired. After I successfully post the form (not missing any required fields) each additional postings will cause OnSuccess to fire even though the validation failed (required fields are missing). The red exclamation point is displayed correctly and the controller "knows" it failed but the ajax OnSuccess doesn't seem to know about the new failure.
ContactUsForm.cshtml (partialView):
#model contactdemo.Models.ContactUsDetails
<div id="formContainer">
#using (Ajax.BeginForm("ContactUsForm", new AjaxOptions { UpdateTargetId = "formContainer", OnSuccess = "displaySuccess" }))
{
<strong>Send To: </strong>
<div>
#Html.DevExpress().ComboBoxFor(model => model.ContactID,
settings =>
{
settings.ShowModelErrors = true;
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.Name = "ContactID";
settings.Properties.ValueField = "ContactID";
settings.Properties.ValueType = typeof(int);
settings.Properties.TextField = "ContactName";
settings.ControlStyle.CssClass = "contactUsCombo";
}).BindList(Session["Names"]).GetHtml()
</div>
<div>
#Html.DevExpress().LabelFor(m => m.Subject).GetHtml()
#Html.DevExpress().TextBoxFor(m => m.Subject,
settings =>
{
settings.ShowModelErrors = true;
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.ControlStyle.CssClass = "subjectText";
}).GetHtml()
</div>
<div>
#Html.DevExpress().LabelFor(m => m.Message).GetHtml()
#Html.DevExpress().MemoFor(m => m.Message,
settings =>
{
settings.ShowModelErrors = true;
settings.Height = 50;
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.ControlStyle.CssClass = "memoText";
}).GetHtml()
</div>
<div>
#Html.DevExpress().Button(
settings =>
{
settings.Name = "btnSubmit";
settings.Text = "Send Message";
settings.UseSubmitBehavior = true;
settings.ControlStyle.CssClass = "contactUsCombo";
}).GetHtml()
</div>
}
HomeController.cs:
namespace contactdemo.Controllers
{
[OutputCacheAttribute(VaryByParam = "*", Duration = 1, NoStore = true)]
public class HomeController : Controller
{
<snip...>
[HttpGet]
[OutputCache(Duration = 60, VaryByParam = "*")]
public ActionResult ContactUsForm()
{
return PartialView(new ContactUsDetails());
}
[HttpPost]
public ActionResult ContactUsForm(ContactUsDetails data)
{
if (ModelState.IsValid)
{
return PartialView(new ContactUsDetails());
}
else
{
return PartialView(data);
}
}
}
Index.cshtml:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script type="text/javascript">
function displaySuccess(result) {
alert("Sent Successfully");
}
</script>
Make sure that inside your displaySuccess callback you reattach the unobtrusive validation handler to the newly added contents to the DOM:
function displaySuccess(result) {
$('#formContainer form').removeData('validator');
$('#formContainer form').removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('#formContainer form');
alert('Sent Successfully');
}
The reason you need to do this is because you are refreshing the contents of your DOM with the new partial after an AJAX callback and the unobtrusive validation framework has no way of knowing those new elements unless you tell it to. You might also take a look at a similar answer.

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?

Attach a Javascript function to an OOTB ribbon button

I want to attach a custom javascript function to the out of the box "Download a copy" ribbon button. This is to provide analytics for file downloads done through the ribbon button.
I tried this code, but it doesn't seem to work:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script>
_spBodyOnLoadFunctionNames.push("Trackdownloads");
function Trackdownloads(){
debugger;
$("a[id='Ribbon.Documents.Copies.Download-Large']").live( "click",
function() {
alert('hello');
}
);
}
</script>
Any idea how to get this to work?
Found a solution to my problem.
Actually, attaching a javascript function to the button is not the right way to implement this.
The correct implementation is to replace the OOTB button with a custom button, and call a custom javascript function to carry out the desired action.
http://msdn.microsoft.com/en-us/library/ff407619.aspx
If you do want to override a button in the ribbon. Creating a custom Page Component is a good idea. Example:
Type.registerNamespace('Company.Project.Ribbon.PageComponent');
Company.Project.Ribbon.PageComponent = function (PageComponentId) {
this._pageComponentId = PageComponentId;
Company.Project.Ribbon.PageComponent.initializeBase(this);
}
Company.Project.Ribbon.PageComponent.prototype =
{
_pageComponentId: "PageComponentIDHolder",
getId: function () {
return this._pageComponentId;
},
init: function () {
this._myCommandList = ['DownloadCopy'];
this._myHandledCommands = {};
this._myHandledCommands['DownloadCopy'] = Function.createDelegate(this, this.CMD1_Handler);
},
getFocusedCommands: function () {
return this._myCommandList;
},
getGlobalCommands: function () {
return this._myCommandList;
},
canHandleCommand: function (commandId) {
var canHandle = this._myHandledCommands[commandId];
if (canHandle)
return true;
else
return false;
},
handleCommand: function (commandId, properties, sequence) {
return this._myHandledCommands[commandId](commandId, properties, sequence);
},
isFocusable: function () {
return true;
},
CMD1_Handler: function (commandId, properties, sequence) {
alert('Download a copy-button was clicked');
}
}
Company.Project.Ribbon.PageComponent.registerClass('Company.Project.Ribbon.PageComponent', CUI.Page.PageComponent)
NotifyScriptLoadedAndExecuteWaitingJobs("/_layouts/custompagecomponents/PageComponent.js");
function init2() {
var instance = new Company.Project.Ribbon.PageComponent("ComponentID");
SP.Ribbon.PageManager.get_instance().addPageComponent(instance);
}
function init1() {
ExecuteOrDelayUntilScriptLoaded(init2, 'sp.ribbon.js');
}
ExecuteOrDelayUntilScriptLoaded(init1, '/_layouts/custompagecomponents/PageComponent.js');

Resources