JSF Primefaces backbean component update without refreshing the page

Reading Time: 3 minutes

At work I’ve come t resolve a necessity which was in a payment screen updating a price panel component right after customers fires the promotion button to apply a price deduction which is controlled and price update is applied from the back bean. the panel you see on the right hand side will be affected

Before Update

memberupdate1

After Update

memberupdate2

Frontend

<h:form id="primeForm" styleClass="default-form">
                <!-- Package Panel begin -->
                <p:panel header="#{msg.membership_details_confirmation}"
                    widgetVar="packageVar" styleClass="cart animation2" id="package">
                    <p:outputPanel id="packageInfo" styleClass="detail-departments">
                        <h:outputText styleClass="staticText"
                            value="#{msg.membership_details_you_selected}" />
                        <h:outputText styleClass="staticText"
                            value="#{msg.member_club_name}" />
                        <h:outputText styleClass="selectedClub"
                            value="#{memberController.order.club.name}" />
                        <hr />
                        <h:outputText styleClass="staticText" value="#{msg.membership}" />
                        <h:outputText styleClass="selectedClub"
                            value="#{memberController.order.membership.localizedDescription}" />
                        <div style="clear: both" />
                        <div class="membershipDescrition">

                            <h:outputText styleClass="staticText"
                                style="padding-top: 10px; font-weight: bold !important;"
                                value="#{memberController.order.membership.type == 'MONTHLY' ? msg.monthly : msg.yearly} #{msg.member_charges}" />
                            <h:outputText styleClass="selectedUnit"
                                value="#{memberController.order.membership.type == 'MONTHLY' ? memberController.calculatedPrice.additionalPrice : memberController.calculatedPrice.totalPriceWithAdditional} #{memberController.order.membership.type == 'MONTHLY' ? msg.payment_monthly_pay : msg.payment_tl} " />
                            <div style="width: 80%; display: inline-block; margin-top: 10px;"
                                class="packageInfoColumn">
                                <h:outputText styleClass="tc-message"
                                    value="#{msg.member_as_follows}" />
                            </div>
                            <div style="width: 55%; display: inline-block"
                                class="packageInfoColumn">1- #{msg.membership_joining_fee}</div>
                            <div style="display: inline-block" class="packagePrice">#{memberController.calculatedPrice.enrollmentPrice}
                                #{msg.payment_tl}</div>

                            <!-- Non presale club -->
                            <h:panelGroup
                                rendered="#{memberController.calculatedPrice.preSaleClub == false}">
                                <div style="width: 55%; display: inline-block"
                                    class="packageInfoColumn">2- #{msg.member_prorated}</div>
                                <div style="display: inline-block" class="packagePrice">#{memberController.calculatedPrice.currentMonthPrice}
                                    #{msg.payment_tl}</div>
                            </h:panelGroup>

                            <!-- Presale club -->
                            <h:panelGroup
                                rendered="#{memberController.calculatedPrice.preSaleClub == true}">
                                <div style="width: 55%; display: inline-block"
                                    class="packageInfoColumn">
                                    2-
                                    <h:outputText
                                        value="#{memberController.order.membership.type == 'MONTHLY' ? msg.member_monthly_charge : msg.member_annual_charge}" />
                                </div>
                                <div style="display: inline-block" class="packagePrice">#{memberController.calculatedPrice.grandTotal}
                                    #{msg.payment_tl}</div>
                            </h:panelGroup>

                            <!-- Monthly  -->
                            <h:panelGroup
                                rendered="#{memberController.order.membership.type == 'MONTHLY' and memberController.calculatedPrice.additionalPriceVisible == true} ">
                                <div style="width: 55%; display: inline-block"
                                    class="packageInfoColumn">3-
                                    #{msg.member_additionaly_monthly}</div>

                                <div style="display: inline-block" class="packagePrice">#{memberController.calculatedPrice.additionalPrice}
                                    #{msg.payment_tl}</div>
                            </h:panelGroup>

                            <!-- Annually  -->
                            <h:panelGroup
                                rendered="#{memberController.order.membership.type == 'YEARLY' and memberController.calculatedPrice.totalPrice != null and memberController.calculatedPrice.preSaleClub == false}">
                                <div style="width: 55%; display: inline-block"
                                    class="packageInfoColumn">3-
                                    #{msg.member_additionaly_yearly}</div>

                                <div style="display: inline-block" class="packagePrice">#{memberController.calculatedPrice.totalPrice}
                                    #{msg.payment_tl}</div>
                            </h:panelGroup>


                            <p:outputPanel styleClass="packageInfoRow">
                                <div
                                    style="width: 55%; display: inline-block; font-weight: bold !important;"
                                    class="packageInfoColumn">#{msg.member_total_currenly_charges}
                                </div>
                                <div style="display: inline-block" class="packagePrice">
                                    <h:outputText styleClass="entranceFee"
                                        value="#{memberController.calculatedPrice.grandTotal} #{msg.payment_tl}" />
                                </div>
                            </p:outputPanel>


                            <p:outputPanel styleClass="packageInfoRow"
                                style="margin-bottom: 50px;">
                                <div style="display: inline-block; margin-top: 10px;"
                                    class="packageInfoColumn">
                                    <h:outputText styleClass="tc-message"
                                        value="#{memberController.order.membership.type == 'MONTHLY' ? msg.member_package_monthly_message : ''} " />
                                </div>
                            </p:outputPanel>

                            <p:commandButton value="#{msg.con}" update="primeForm"
                                styleClass="green-button"
                                action="#{memberController.saveAndContinue()}"
                                icon="ui-icon-check" />
                        </div>
                    </p:outputPanel>

            </h:form>

Back bean

	public void addPromotionCode() {
		if (promotionCode != null) {
			LOG.info("validating the promotion code : " + promotionCode);
			BLPriceResponse blPriceResponse = callPricingService(promotionCode);
			if (blPriceResponse.isResponse()) {
				LOG.info("valid promotion code : " + promotionCode);
				// apply the code to the session info
				sessionInformation.setPriceResponse(blPriceResponse);
				// recalculate the price
				calculatePrice();
				// update the form
				RequestContext.getCurrentInstance().update("primeForm:package");
				LOG.info("calculated price : " + calculatedPrice.toString());
			} else {
				LOG.info("invalid promotion code : " + promotionCode);
				// the code does not work paint it to red
				MessageUtil.addMessage("primeForm:promotionCode", FacesMessage.SEVERITY_ERROR,
						OLSConstants.PROMOTION_CODE_NOT_VALID, OLSConstants.PROMOTION_CODE_NOT_VALID);
				promotionCode = null;
				RequestContext.getCurrentInstance().execute("addError('pCodeVar')");
			}
		}
	}

Explanation

here in this situation we have defined the form an id called “primeForm” and the component whose complete values will be refreshed is defined in between this form tag with the id called “package”. In the controller where the method invoked “addPromotionCode” particularly check the promotion code, if the code is accurate then in the method “calculatePrice” the regarding bean is updated. Then by invoking update method on the requst context interface, we first reach out the first element, then with the colon we delimiter and reach out to the child element “package” which will be affected.

 

Displaying messagebox from backing bean

Reading Time: 1 minute

This piece of code snippet will initially hide the primefaces dialog box, then in any action from the backing bean, it will be activated and seen

Back bean

RequestContext context = RequestContext.getCurrentInstance();
			context.execute("PF('dlgBlackListVar').show();");

View

<p:dialog id="dlgBlackList" widgetVar="dlgBlackListVar"
						header="#{msg.member_blacklist_header}" showEffect="clip" modal="true"
						visible="false">
						<h:outputText value="#{msg.member_blacklist_content}" />
					</p:dialog>

Primefaces navigating in between min and max dates

Reading Time: 1 minute

Today at work I was stuck at demonstrating all the possible years which are given by min and max date ranges in the backing bean in primefaces and jsf combo. So as default primefaces calendar component only displays

just set the year range to maximize the value the way you wish

								<p:calendar id="birthdate"
									value="#{memberController.order.birthdate}"
									yearRange="c-70:c+10"
									placeholder="#{msg.member_birthdate}" locale="tr"
									pattern="dd/MM/yyyy" mask="true" effect="fold"
									widgetVar="birthdateVar"
									styleClass="#{not component.valid ? 'ui-date-invalid default-input-date' : 'default-input-date'}"
									required="true"
									mindate="#{memberController.getBirthdateBegin()}"
									maxdate="#{memberController.getBirthdateEnd()}"
									navigator="true">
									<f:convertDateTime pattern="dd/MM/yyyy" />
								</p:calendar>

 

JSF Multiple EL String concatenation

Reading Time: 1 minute

Today I’ve come to experience an usual situation which did result me to concatenate two strings values exceptionally derived from different EL sources. One is derived from database/controller the other is the messages/language sources.

As you apprehend the situation from the below screenshot, Annual and Monthly values which pointed in the red color are fetched from the persistence unit, and the rest is fetched from the resources bundle.

This code snipped allowed me to bind different string sources and the outcome is shown as like below “Annual Membership” and “Monthly Membership”

 

JSF_EL_CONCAT

 

Code Snippet

 

To mind the version requirement, I’d used this implementation JSF version 2.x

 

Loading CSS JS Resources in JSF

Reading Time: 1 minute

 

JSF Project JS CSS Resource

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
    <h:outputStylesheet name="basetemplate.css" library="css"/>
    <h:outputStylesheet name="shCore.css" library="css"/>
    <h:outputStylesheet name="shThemeDefault.css" library="css"/>
    <h:outputScript name="shCore.js" library="js"/>
    <h:outputScript name="shBrushXml.js" library="js"/>
    <h:outputScript name="shBrushJScript.js" library="js"/>
</h:head>

 

Catching Primefaces form elements in jquery and preventing copy paste and cut operations

Reading Time: 1 minute

xhtml

<p:inputText id="firstName" placeholder="#{msg.member_name}"
								value="#{memberController.order.firstName}" size="30"
								maxlength="30" widgetVar="firstNameVar" required="true"
								styleClass="#{not component.valid ? 'ui-input-invalid default-input-text' : 'default-input-text'}"
								onkeypress="return disallowNonAlphabethCharacters(event);">
								<p:ajax delay="1000" event="keyup"
									oncomplete="rc([{name: 'component', value: ':primeForm:firstName'},
                        {name: 'widget', value: 'firstNameVar'}]);" />
							</p:inputText>

javascript

<script type="text/javascript">
				 $( document ).ready(function() {
					 PF('firstNameVar').jq.bind('cut copy paste', function(e) {
							e.preventDefault();
						});
					 
					 PF('firstNameVar').jq.bind("contextmenu", function(e) {
			                e.preventDefault();
			            });
				    });
					</script>

Disabling non alphabet characters while entering the input

Reading Time: 1 minute
<p:inputText id="firstName" placeholder="#{msg.member_name}"
								value="#{memberController.order.firstName}" size="30"
								maxlength="30" widgetVar="firstNameVar" required="true"
								styleClass="#{not component.valid ? 'ui-input-invalid default-input-text' : 'default-input-text'}"
								onkeypress="return disallowNonAlphabethCharacters(event);">
								<p:ajax delay="1000" event="keyup"
									oncomplete="rc([{name: 'component', value: ':primeForm:firstName'},
                        {name: 'widget', value: 'firstNameVar'}]);" />
							</p:inputText>

 

Javascript

<script language="javascript" type="text/javascript">
					// <![CDATA[
					function disallowNonAlphabethCharacters(e) {
						var charCode;
						if (window.event)
							charCode = window.event.keyCode; //for IE
						else
							charCode = e.charCode; //for firefox
						if (charCode == 32) //for &lt;space&gt; symbol
							return true;
						if (charCode == 286)
							return true;
						if (charCode == 287)
							return true;
						if (charCode == 220)
							return true;
						if (charCode == 252)
							return true;
						if (charCode == 350)
							return true;
						if (charCode == 351)
							return true;
						if (charCode == 304)
							return true;
						if (charCode == 105)
							return true;
						if (charCode == 305)
							return true;
						if (charCode == 73)
							return true;
						if (charCode == 214)
							return true;
						if (charCode == 246)
							return true;
						if (charCode == 199)
							return true;
						if (charCode == 231)
							return true;
						if (charCode > 31 && charCode < 65) //for characters before 'A' in ASCII Table
							return false;
						if (charCode > 90 && charCode < 97) //for characters between 'Z' and 'a' in ASCII Table
							return false;
						if (charCode > 122) //for characters beyond 'z' in ASCII Table
							return false;
						return true;
						// console.log(charCode);
						// // console.log(e);

						// 					        231
					}
					// ]]>
				</script>

Forwarding to a page from controller

Reading Time: 1 minute

This is very useful when you compare that a passed object is null in the forthcoming controller you may directly forward user to a different page or maybe assign a message regarding the issue that the user had faced this error it depends on your development favorite

FacesContext.getCurrentInstance().getExternalContext().redirect("index.jsf");

 

Passing objects between managed beans&controllers

Reading Time: 1 minute

in the source controller add your object into faces session map interface and identify it with a name

FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("category", category);

then in the target controller to acquire the object do the following

Category category = (Category) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("category");

Adding resources css&js into the page

Reading Time: 1 minute

Importing resources files for instance css and js can be really painful, which actually caused me tons of trouble to implement them. I’ve checked out many of examples on the internet, all they say it to create a folder named css for css files and js folder for javascript files in src/main/resources. So I did give it a shot, but sadly did not work on me.

So eventually I was testing things out and finally I’ve come up with the solution. The below graphic shows to where create the folder underneath webapp create folder called resources once again under that folder create your folders css and js for script and style schema files. Study the graphic below

IntelliJResourcesJSF

and then in your .xhtml file

CSS call

<h:head>
    <title>Home!!</title>
    <h:outputStylesheet library="css" name="styles.css" />
</h:head>

JS call

<h:head>
    <title>Home!!</title>
    <h:outputScript library="js" name="loader.js" />
</h:head>