Thursday, 26 July 2012

My date box Component

Using jquery plugin, we will create our date box component in ZK and apply mask and water mark. You can download the jquery plugin from the following site
http://digitalbush.com/projects/masked-input-plugin/
http://digitalbush.com/projects/watermark-input-plugin/

 

Environment

  1. Eclipse 3.7 Indigo IDE
  2. Hibernate 4.1.1
  3. JavaSE 1.6
  4. MySQL 5.1
Project Name :MyDateComponent
Project Structure:

image

Step 1: 
ZK + Hibernate Setup
Please follow this post to setup the Project and related jar files needed for this example
Step 2:
SQL Setup. Create the following table in my sql.

CREATE TABLE `emp_master` (
  `ID` BIGINT(20) NOT NULL AUTO_INCREMENT,
  `EMP_NAME` VARCHAR(255) DEFAULT NULL,
  `DOB` DATE DEFAULT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=INNODB DEFAULT CHARSET=latin1

Step 3:
In the Webcontent folder, create a folder called js and attached the downloaded the plugin.
image

You can also download the files from my site as follows
Download this and this

Step 4:
Let us create all our classes and zul files

Datebox.java


package component;

import org.zkoss.zul.Textbox;

public class Datebox extends Textbox {

private static final long serialVersionUID = 1L;

public Datebox() {

setWidgetListener("onBind", "jq(this).mask('99/99/9999');jq(this).Watermark('mm/dd/yyyy','gray');");
}

}

MyDateFormatConverter.java




package component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.zkoss.bind.BindContext;
import org.zkoss.bind.Converter;
import org.zkoss.zk.ui.Component;


@SuppressWarnings("rawtypes")
public class MyDateFormatConverter implements Converter {
/**
* Convert Date to String.
*
* @param val
* date to be converted
* @param comp
* associated component
* @param ctx
* bind context for associate Binding and extra parameter (e.g.
* format)
* @return the converted String
*/

private static SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

public Object coerceToUi(Object val, Component comp, BindContext ctx) {
final Date date = (Date) val;
return date == null ? null : sdf.format(date);
}

/**
* Convert String to Date.
*
* @param val
* date in string form
* @param comp
* associated component
* @param ctx
* bind context for associate Binding and extra parameter (e.g.
* format)
* @return the converted Date
*/
public Object coerceToBean(Object val, Component comp, BindContext ctx) {
final String date = (String) val;

try {
return date == null ? null : sdf.parse(date);
} catch (ParseException e) {
comp.invalidate();
return null;

}
}

}

EmployeeDAO.java


package domainDAO;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Query;
import HibernateUtilities.HibernateUtil;
import mydomain.employee;

public class EmployeeDAO {

@SuppressWarnings("unchecked")
public List<employee> getAllEmployee() {
List<employee> allrecords = null;
try {
Session session = HibernateUtil.beginTransaction();
Query q1 = session.createQuery("from employee");
allrecords = q1.list();
HibernateUtil.CommitTransaction();
} catch (RuntimeException e) {
e.printStackTrace();
}
return allrecords;
}

public void saveOrUpdate(employee p1) {

try {
Session session = HibernateUtil.beginTransaction();
session.saveOrUpdate(p1);
HibernateUtil.CommitTransaction();
} catch (RuntimeException e) {
e.printStackTrace();
}

}
}


EmployeeCRUDVM.java


package domainVMS;

import java.util.HashMap;
import java.util.Map;

import mydomain.employee;

import org.zkoss.bind.BindUtils;

import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.ExecutionArgParam;
import org.zkoss.bind.annotation.Init;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Window;
import domainDAO.EmployeeDAO;

public class EmployeeCRUDVM {

@Wire("#win")
private Window win;

private employee selectedEmployee;
private boolean makeAsReadOnly;


public employee getSelectedEmployee() {
return selectedEmployee;
}

public void setSelectedEmployee(employee selectedEmployee) {
this.selectedEmployee = selectedEmployee;
}

public boolean isMakeAsReadOnly() {
return makeAsReadOnly;
}
public void setMakeAsReadOnly(boolean makeAsReadOnly) {
this.makeAsReadOnly = makeAsReadOnly;
}

@Init
public void initSetup(@ContextParam(ContextType.VIEW) Component view,
@ExecutionArgParam("selectedEmployee") employee selectedEmployee,
@ExecutionArgParam("recordMode") String recordMode) {
Selectors.wireComponents(view, this, false);
if (selectedEmployee== null)
this.selectedEmployee = new employee();
else
this.selectedEmployee = selectedEmployee;

if (recordMode == "READ") {
setMakeAsReadOnly(true);
win.setTitle(win.getTitle() + " (Readonly)");
}

}

@Command
public void save() {
new EmployeeDAO().saveOrUpdate(this.selectedEmployee);
Map args = new HashMap();
args.put("newadded", this.selectedEmployee);
BindUtils.postGlobalCommand(null, null, "refreshList", args);
win.detach();
}

@Command
public void closeThis() {
win.detach();
}
}


EmployeeListVM.java

package domainVMS;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.GlobalCommand;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Executions;
import domainDAO.EmployeeDAO;
import mydomain.employee;

public class EmployeeListVM {

private List<employee> employees= new ArrayList<employee>();
private employee curSelectedEmployee;

public List<employee> getallEmployees() {
return employees;
}


public employee getCurSelectedEmployee() {
return curSelectedEmployee;
}

public void setCurSelectedEmployee(employee curSelectedEmployee) {
this.curSelectedEmployee = curSelectedEmployee;
}

@Init
public void initSetup() {
employees= new EmployeeDAO().getAllEmployee();

}

@Command
public void editThisEmployee () {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("selectedEmployee", curSelectedEmployee);
map.put("recordMode", "EDIT");
Executions.createComponents("EmployeeCRUD.zul", null, map);
}

@Command
public void openAsReadOnly()
{
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("recordMode", "READ");
map.put("selectedEmployee", curSelectedEmployee);
Executions.createComponents("EmployeeCRUD.zul", null, map);

}

@Command
public void addNewEmployee() {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("selectedEmployee", null);
map.put("recordMode", "NEW");
Executions.createComponents("EmployeeCRUD.zul", null, map);
}


@GlobalCommand
@NotifyChange("allEmployees")
public void refreshList(@BindingParam("newadded") employee p1)
{
employees.add(p1);
}

}


employee.java


package mydomain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = "emp_master")
public class employee {

@Id
@GeneratedValue
private int ID;
@Column(name = "EMP_NAME")
private String employeeName;

@Column(name = "DOB")
@Temporal(TemporalType.DATE)
private Date dateOfBirth;


public Date getDateOfBirth() {
return dateOfBirth;
}

public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}

public int getID() {
return ID;
}

public void setID(int iD) {
ID = iD;
}

public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}

}


hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/sampledb</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>

<!-- Mapping Classes -->
<mapping class="mydomain.employee" />

</session-factory>
</hibernate-configuration>


Please change the DB Name, username and password according to your setup.

EmployeeList.zul


<?page title="Listitem MVVM Demo with Hibernate" contentType="text/html;charset=UTF-8"?>
<zk>
<style>
.z-listcell.red .z-listcell-cnt, .z-label.red{ color:red; }

/* Start: Action Images- Edit
---------------------------------------------- */

.fimageedit { width: 25px; background-image:
url('./images/icon-edit.png'); background-repeat: no-repeat;
border: 0 none; cursor: pointer; }

/* End: Action Images - Edit
---------------------------------------------- */


/* Start: Action Images- Delete
---------------------------------------------- */

.fimageDelete { width: 25px; background-image:
url('./images/icon-trash-red.png'); background-repeat:
no-repeat; border: 0 none; cursor: pointer; }

/* End: Action Images - Delete
---------------------------------------------- */


/* Start: Action Images- Active
---------------------------------------------- */

.fimageActive { width: 25px; background-image:
url('./images/icon-enable.png'); background-repeat: no-repeat;
border: 0 none; cursor: pointer; }

/* End: Action Images - Active
---------------------------------------------- */

/* Start: Action Images- Inactive' ]

---------------------------------------------- */

.fimageInactive { width: 25px; background-image:
url('./images/icon-disable.png'); background-repeat: no-repeat;
border: 0 none; cursor: pointer; }

/* End: Action Images - InActive
---------------------------------------------- */

.z-listcell.highlightcell .z-listcell-cnt,
.z-label.highlightcell { color:blue; cursor: pointer; }


</style>
<window title="Listitem MVVM Demo with Hibernate" border="normal"
apply="org.zkoss.bind.BindComposer"
viewModel="@id('myvm') @init('domainVMS.EmployeeListVM')">
<div>
<button label="Add Employee"
onClick="@command('addNewEmployee')" />
</div>
<separator />

<listbox id="test" model="@load(myvm.allEmployees)"
selectedItem="@bind(myvm.curSelectedEmployee)">
<listhead sizable="true">
<listheader label="Name" width="400px"
sort="auto(employeeName)" />
<listheader label="Date of Birth" />
<listheader label="Action" />
</listhead>
<template name="model" var="p1">
<listitem>
<listcell label="@load(p1.employeeName)"
onClick="@command('openAsReadOnly')" sclass="highlightcell" />
<listcell label="@load(p1.dateOfBirth) @converter('component.MyDateFormatConverter')" />
<listcell>
<hbox spacing="20px">
<image sclass="fimageDelete" />
<image sclass="fimageedit"
onClick="@command('editThisEmployee')" />
</hbox>
</listcell>
</listitem>
</template>
</listbox>
</window>
</zk>





EmployeeCRUD.zul

<zk>
<window id="win" title="Employee" width="520px" height="220px"
border="normal" minimizable="false" mode="modal" maximizable="false"
closable="true" action="show: slideDown;hide: slideUp"
apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('domainVMS.EmployeeCRUDVM')">
<separator />
<label value="Employee information" />
<separator />
<panel width="100%">
<panelchildren>
<separator />
<grid width="99.5%">
<columns>
<column label="" width="150px" />
<column label="" />
</columns>
<rows>
<row>
<hbox>
<label value="Name" />
<label value="*" />
</hbox>
<textbox name="name"
readonly="@load(vm.makeAsReadOnly)"
value="@bind(vm.selectedEmployee.employeeName)" cols="50" />
</row>
<row>
<hbox>
<label value="DOB" />
<label value="*" />
</hbox>
<fdatebox id="txtDOB" name="txtDOB"
readonly="@load(vm.makeAsReadOnly)"
value="@bind(vm.selectedEmployee.dateOfBirth) @converter('component.MyDateFormatConverter')" />
</row>
</rows>
</grid>
</panelchildren>
</panel>
<separator />
<div align="center">
<button id="submit" label="Submit"
onClick="@command('save')" visible="@load(not vm.makeAsReadOnly)" />
<button id="cancel"
label="@load(vm.makeAsReadOnly ?'Ok':'Cancel')"
onClick="@command('closeThis')" />
</div>
</window>
</zk>




my-addon.xml

<?xml version="1.0" encoding="UTF-8"?>
<language-addon>
<addon-name>anyname</addon-name>
<language-name>xul/html</language-name>

<javascript src="/js/jquery.maskedinput-1.3.js" />
<javascript src="/js/watermarkinput.js" />

<component>
<component-name>fdatebox</component-name>
<component-class>component.Datebox
</component-class>
<extends>textbox</extends>
</component>


</language-addon>

 

zk.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--
Created by ZK Studio
-->

<zk>
<device-config>
<device-type>ajax</device-type>
<timeout-uri>/timeout.zul</timeout-uri><!-- An empty URL can cause the browser to reload the same URL -->
</device-config>

<language-config>
<addon-uri>/my-addon.xml</addon-uri>
</language-config>


</zk>




Now you can run EmployeeList.zul  file
Output:

image

image


You can download the source code here.


 





 

4 comments:

  1. windows 10 activation phone support , microsoft visio professional 2016 order , windows 10 product key activated free , windows 10 activation 0xc004c003 blocked , windows 10 pro serial key free , windows 10 product key 4 , vmware workstation 11 to buy , windows 7 profession key , t7xWIO

    office 2016 product serial free

    windows 10 enterprise key

    office 2016 product key

    Windows 10 product key code sale

    ReplyDelete
  2. I delight in the content on your internet site. Thanks for your time!

    Generic Viagra

    ReplyDelete
  3. We are a third party technical support service. Avast Customer Support is here to help you out with the whole procedure to Download Avast Antivirus online, We not only fix your Avast Support related issues but will guide with how to get started with your new Avast product once it gets installed successfully. Call on our Toll Free no. 1 855 966 3855
    Gmail Customer service is a third party technical support service for Gmail users when they face any technical issue or error in their Gmail account. Our Gmail Customer Support team solves issues like forgot Gmail account password, Gmail configuration or Sync issues, recover deleted emails and many more. Toll Free number (800) 986-9271
    How you install or reinstall Office 365 or Office 2016 depends on whether your Office product is part of an Office for home or Office for business plan. If you're not sure what you have, see what office com setup products are included in each plan and then follow the steps for your product. The steps below also apply if you're installing a single, stand-alone Office application such as Access 2016 or Visio 2016. Need Help with office setup Enter Product Key? Call 1-800-000-0000 Toll Free
    Norton Tech Support is a third party service provider and not in any way associated with Norton or any of its partner companies. We offer support for Norton products and sell subscription based additional warranty on computer and other peripheral devices. Call our Toll Free number 1 855 966 3855
    Other Services
    Norton Toll Free , Office-Setup , office.com/setup.

    ReplyDelete