Primefaces CommandButton

Filed Under: JSF

Today we will look into primefaces CommandButton. Primefaces has a huge components library.

Primefaces CommandButton

Primefaces CommandButton is an extended version of standard commandButton. I have used p:commandButton in many Primefaces tutorials in earlier posts.

Primefaces CommandButton is an extended version of h:commandButton that’s provided by Reference Implementation of JSF.

Tag CommandButton
Component Class org.primefaces.component.commandbutton.CommandButton
Component Type org.primefaces.component.CommandButton
Component Family org.primefaces.component
Renderer Type org.primefaces.component.CommandButtonRenderer
Renderer Class org.primefaces.component.commandbutton.CommandButtonRenderer

Primefaces CommandButton Attributes

Name Default Type Description
id null String Unique identifier of the component
rendered true Boolean Boolean value to specify the rendering of the component, when set to false component will not be rendered.
binding null Object An el expression that maps to a server side UIComponent instance in a backing bean
value null String Label for the button
action null MethodExpr/ String A method expression or a String outcome that’d be processed when button is clicked.
actionListener null MethodExpr An actionlistener that’d be processed when button is clicked.
immediate false Boolean Boolean value that determines the phaseId, when true actions are processed at apply_request_values, when false at invoke_application phase.
type submit String Sets the behavior of the button.
ajax true Boolean Specifies the submit mode, when set to true(default), submit would be made with Ajax.
async false Boolean When set to true, ajax requests are not queued.
process null String Component(s) to process partially instead of whole view.
update null String Component(s) to be updated with ajax.
onstart null String Client side callback to execute before ajax request is begins.
oncomplete null String Client side callback to execute when ajax request is completed.
onsuccess null String Client side callback to execute when ajax request succeeds.
onerror null String Client side callback to execute when ajax request fails.
global true Boolean Defines whether to trigger ajaxStatus or not.
delay null String If less than delay milliseconds elapses between calls to request() only the most recent one is sent and all other requests are discarded. If this option is not specified, or if the value of delay is the literal string ‘none’ without the quotes, no delay is used.
partialSubmit false Boolean Enables serialization of values belonging to the partially processed components only.
resetValues false Boolean If true, local values of input components to be updated within the ajax request would be reset.
ignoreAutoUpdate false Boolean If true, components which autoUpdate=”true” will not be updated for this request. If not specified, or the value is false, no such indication is made.
style null String Inline style of the button element.
styleClass null String StyleClass of the button element.
onblur null String Client side callback to execute when button loses focus.
onchange null String Client side callback to execute when button loses focus and its value has been modified since gaining focus.
onclick null String Client side callback to execute when button is clicked.
ondblclick null String Client side callback to execute when button is double clicked.
onfocus null String Client side callback to execute when button receives focus.
onkeydown null String Client side callback to execute when a key is pressed down over button.
onkeypress null String Client side callback to execute when a key is pressed and released over button.
onkeyup null String Client side callback to execute when a key is released over button.
onmousedown null String Client side callback to execute when a pointer button is pressed down over button.
onmousemove null String Client side callback to execute when a pointer button is moved within button.
onmouseout null String Client side callback to execute when a pointer button is moved away from button.
onmouseover null String Client side callback to execute when a pointer button is moved onto button.
onmouseup null String Client side callback to execute when a pointer button is released over button.
onselect null String Client side callback to execute when text within button is selected by user.
accesskey null String Access key that when pressed transfers focus to the button.
alt null String Alternate textual description of the button.
dir null String Direction indication for text that does not inherit directionality. Valid values are LTR and RTL.
disabled false Boolean Disables the button.
image null String Style class for the button icon. (deprecated: use icon)
label null String A localized user presentable name.
lang null String Code describing the language used in the generated markup for this component.
tabindex null Integer Position of the button element in the tabbing order.
title null String Advisory tooltip information.
readonly false Boolean Flag indicating that this component will prevent changes by the user.
icon null String Icon of the button as a css class.
iconPos left String Position of the icon.
inline false String Used by PrimeFaces mobile only.
escape true Boolean Defines whether label would be escaped or not.
widgetVar null String Name of the client side widget.

Primefaces CommandButton Example

Primefaces CommandButton usage isn’t vary different from the standard JSF implementation. By default commandButton submits its enclosing form with ajax capabilities.

simpleCommandButton.xhtml


<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
</h:head>
<h:form>
	<p:commandButton value="Do Action" action="#{commandButtonManagedBean.doSomeAction}"></p:commandButton>
</h:form>
</html>

CommandButtonManagedBean.java


package com.journaldev.primefaces.beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class CommandButtonManagedBean {
	public String doSomeAction(){
		// Do any action that you would.
		System.out.println("Hello JournalDev !");
		// Returns outcome
		return "";
	}
}

Primefaces CommandButton Example

Rest & Push CommandButtons

Primefaces CommandButton provides a lot of features. You can use CommandButton to reset the form or to invoke custom JavaScript without causing an ajax/non-ajax request to be initiated.

rest-push-CommandButton.xhtml


<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
	<script>
		function justCall(){
			alert('Push Action');
		}
	</script>
</h:head>
<h:form>
	Enter your username: <p:inputText value="#{commandButtonManagedBean.username}"></p:inputText>
	<br/>
	Enter your username: <p:password value="#{commandButtonManagedBean.password}"></p:password>
	<br/>
	<p:commandButton value="Login" action="#{commandButtonManagedBean.doSomeAction}"></p:commandButton>
	#{''}
	<p:commandButton value="Rest" type="reset"></p:commandButton>
	#{''}
	<p:commandButton value="Push" type="button" onclick="justCall();"></p:commandButton>
</h:form>
</html>

CommandButtonManagedBean.java


package com.journaldev.primefaces.beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class CommandButtonManagedBean {

	private String username = "";
	private String password = "";

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String doSomeAction(){
		// Do any action that you would.
		System.out.println("Entered Username :: "+username);
		System.out.println("Entered Password :: "+password);
		// Returns outcome
		return "";
	}
}

Primefaces CommandButton - Simple Action - Submit Enclosed Form

Primefaces CommandButton - Rest And Push Commands

Primefaces CommandButton Ajax & Non-Ajax

Primefaces CommandButton has built-in ajax capabilities. By default the commandButton submits the enclosed form with ajax. It can be configured to submit form without ajax by setting ajax attribute to false. When ajax attribute is set to false, form is submitted in a regular full page refresh.

Two attributes are used in conjunction with ajax – update and process.

Update attribute is used to partially update other component(s) after ajax response is received. Update attribute takes component(s) identifiers delimited with whitespace-separated style.

Process attribute is used to partially execute the jsf lifecycle upon those component(s) mentioned. The executed component(s) are also identified using whitespace-separated manner. It’s possible to update any of standard jsf lifecycle using the same Primefaces ajax response.

ajax-nonAjax-UpdateStandardJSF.xhtml


<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
	<script>
		function justCall(){
			alert('Push Action');
		}
	</script>
</h:head>
<h:form>
	<p:growl id="primefacesMessage"></p:growl>
	<h:messages id="standardMessage"></h:messages>
	Enter your username: <p:inputText id="username" value="#{commandButtonManagedBean.username}"></p:inputText>
	<br/>
	Enter your username: <p:password id="password" value="#{commandButtonManagedBean.password}"></p:password>
	<br/>
	<p:commandButton value="Non Ajax Command - Refresh Whole Form"
		action="#{commandButtonManagedBean.doSomeAction}" ajax="false"></p:commandButton>
	#{''}
	<p:commandButton value="Ajax Command - Refresh Specific Form's Component(s)"
		action="#{commandButtonManagedBean.updateMessage}" update="primefacesMessage"></p:commandButton>
</h:form>
</html>

CommandButtonManagedBean.java


package com.journaldev.primefaces.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class CommandButtonManagedBean {

	private String username = "";
	private String password = "";

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String doSomeAction(){
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Message Updated !"));
		// Do any action that you would.
		System.out.println("Entered Username :: "+username);
		System.out.println("Entered Password :: "+password);
		// Returns outcome
		return "";
	}

	public String updateMessage(){
		// Do any action that you would.
		System.out.println("Entered Username :: "+username);
		System.out.println("Entered Password :: "+password);
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Message Updated !"));
		return "";
	}
}

Primefaces commandButton - Ajax - Send Whole Form & Update Whole Form - Non Ajax - Execute Specific Components & Update Specific Components

Here’s detailed explanation for the above code.

  • We’ve used two types of command buttons; one doesn’t support ajax while other does.
  • Non ajax command button causes two messages components to be updated. This type of command submits the whole form and update it as well.
  • Ajax command button causes one message component to be updated. This type of command submits the enclosed form and update specific component as well.
  • We’ve used Primefaces Search Expression for identified the components want to be updated with Ajax response.
  • It’s possible to update the standard message component through using of Primefaces ajax command by adding standard message component’s identifier into update attribute.

Icons & Client Side API

Primefaces provides you the ability to set an icon for your commands in addition to make your commands Enabled/Disabled by using a client JavaScript code. You can refer for ThemeRoller that help you identifying the required icons that you would use.

Method Params Return Type Description
disable() void Disables button
enable() void Enables button

icons-enabled-disabled-CommandButtons.xhtml


<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
<h:head>
	<script name="jquery/jquery.js" library="primefaces"></script>
	<script>
		function copy(){
			PF('copy').disable();
			PF('paste').enable();
		}
		function paste(){
			PF('copy').enable();
			PF('paste').disable();
		}
	</script>
</h:head>
<h:form>
	<p:commandButton widgetVar="copy" icon="ui-icon ui-icon-copy" value="Copy" type="button" onclick="copy();"></p:commandButton>
	<p:commandButton widgetVar="paste" icon="ui-icon ui-icon-document" value="Paste" type="button" onclick="paste();"></p:commandButton>
</h:form>
</html>

Primefaces CommandButton - Set Icon - Client Side API

That’s all for Primefaces CommandButton example. You can download the Primefaces CommandButton example project from below link.

Comments

  1. shyam says:

    I have created two buttons one is feeEnquiry Button and one is Next Button , i want to display a message when next buttong is clicked if FeeEnquiry button is not clicked .

  2. Ectomorph says:

    I’ve been wrestling with commandLink, oncomplete, update and action(Listener) for sometime. I’m doing exactly, more or less, whats demonstrated here except the main body of my jsf is wrapped in a ui:compostion and ui:define – is there any incompatibility using these ?

    Thanks.
    Ecto.

    1. Mohammad says:

      Thanks Ectomorph,

      Just want to recall you that both of composition and define are just a way to build up a template and leverage the concept of creating pages based on that template. According for jsf-2 specification, there’s no incompatibility issues were reported. Even if you are going far and using a newly added concept jsf- custom components, you should see the same behavior for the jsf lifecycle as this is the core of jsf and no way to take it down.

      Let me know if i understand your question properly, so that you get my answer or let me know if you want anything else can i provide it for you.

      Also, i want to give you a good hint to avoid that fighting you’re doing with your JSF pages, and is that to use the facility of Primefaces debugging that’s provided and make sure you’re fully aware of how you could do a phase listening properly as both of these should help you avoiding any type of struggles.

      Thanks a lot for your follow up and hope to hear you once again.

    2. Thien says:

      thank you so much.

  3. Horatiu says:

    Is it possible to call p:fileDownload from inside a p:remoteCommand:

    Since p:remoteCommand doesn’t have the ajax=”false” attribute?

    Thanks in advance

  4. Horatiu says:

    Is it possible to call from inside a :

    Since p:remoteCommand doesn’t have the ajax=”false” attribute?

    Thanks in advance

  5. Umesh says:

    I visited your tutorials few times and i find it very nice and helpful.

    I was facing some issue in my application related with p:confirm dialog.

    I am having a very simple application where records of data is being shown in showRecords page used p:datatable with filters and sorting.
    there is one add record button in showRecordPage which will navigateing to addRecordPage where the user can add the record.
    in addRecordPage one button is given to go back and p:confirm dialog is also there.

    the flow is :
    showRecordPage is there user can use filter and sorting there and if want to add record, will click on addrecord button, and would be navigated to addRecordPage.
    after adding record, if user wants to go back, will click on back button. and will navigated to showRecordPage.

    the problem is :
    when i use back button in addRecordPage and go to showRecordPage, filters are not allowing to put cursor in them. Behaving like disabled textbox and If i am coming back to addRecordPage by clicking addRecord button, textboxes to enter the data are also disabled.

    If i am removing p:confirm dialog, it is working fine.
    I tried with p:confirmdialog also but the same problem.

    I am using primefaces 5.0 jsf 2+ java 7 mozilla 34.0.5

    1. Mohammad Amr says:

      Hi Umesh,

      Let me know if you’re still face the same issue.

      Regards,

  6. Mohammad says:

    Hi Mahender,

    Thanks for your contribution.

    Have you coded any sample ?, please, let me know what the type of obstacles you had.

  7. Mahender says:

    do you have fileDownloaded example for Menu Item. I need to implement monitor download functionality when the user click on menuItem.

    1. Mohammad says:

      Sorry Mahender, i’ve tried to post a code for your but it’s not posted, anyway, just embed your fileDownload within your menuitem and make your menuitem’s ajax attribute equal to false.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages