Grid ,Vaadin 8

Hi Vaadin 8,
I tried all the way to change the Date format(DD-MM-YYYY) in UI but still its displaying in (YYYY-MM-DD) format.
Issues:
1. Date format is not working. I have tried new DateRenderer() : Exception java.util.Date to java.Time.LocalDate can not convert.
2. After deleting any row ,grid is not refreshig. that deleted item is still In-Memory. how to fix it.
3. When I add new row in grid it should display empty full row but I am getting ID as 0 in ID Column.
4. grid.getEditor().addCancelListener() when I am updating any row its working fine,but when new row is added and I am not inserting any data to it, then I am clicking on cancel button , so at that time I want this empty grid shuold get remove from grid.
5. How to do lazyloading in grid.
6. How to do pagination in given grid.
7.How to add popup window in vaadin 7.6.5 using window.
8. How to add radio Button in grid , for examle gender(M,F) or checkbox (M,F) or combobox (M,F)
I have Attached my Source Code ,please once have a look and please suggest me how to fix these issue.


MyUI.java


package com.student.studentgrid;

import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Locale;

import javax.servlet.annotation.WebServlet;

import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.Binder;
import com.vaadin.data.HasValue;
import com.vaadin.data.converter.LocalDateTimeToDateConverter;
import com.vaadin.data.provider.ListDataProvider;
import com.vaadin.data.validator.EmailValidator;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.shared.ui.ValueChangeMode;
import com.vaadin.ui.Button;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.DateField;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Grid.Column;
import com.vaadin.ui.Grid.SelectionMode;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.renderers.DateRenderer;
import com.vaadin.ui.themes.ValoTheme;

/**

  • This UI is the application entry point. A UI may either represent a browser
  • window (or tab) or some part of a html page where a Vaadin application is
  • embedded.
  • The UI is initialized using {@link #init(VaadinRequest)}. This method is
  • intended to be overridden to add component to the user interface and
  • initialize non-component functionality.
    */

@Theme(“mytheme”)
@SuppressWarnings(“deprecation”)
@Title(“Student App”)
public class MyUI extends UI {

public Grid grid = new Grid<>(Student.class);
private Student stud;

@SuppressWarnings(“unchecked”)
@Override
protected void init(VaadinRequest vaadinRequest) {

final Button delete = new Button(“Delete”,FontAwesome.TRASH_O);
delete.setWidth(“100px”);
final TextField filterText = new TextField();
final VerticalLayout layout = new VerticalLayout();
filterText.setPlaceholder(“Filter by name…”);
filterText.setWidth(“138px”);
filterText.setValueChangeMode(ValueChangeMode.LAZY);

Button clearFilterTextBtn = new Button(FontAwesome.TIMES);
clearFilterTextBtn.setDescription(“Clear the current filter”);
clearFilterTextBtn.addClickListener(e → filterText.clear());

filterText.addValueChangeListener(this::onNameFilterTextChange);
CssLayout filtering = new CssLayout();
filtering.addComponents(filterText, clearFilterTextBtn);
filtering.setStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);

delete.setStyleName(ValoTheme.BUTTON_DANGER);
delete.setVisible(false);

Button addStudentBtn = new Button(“Add”, FontAwesome.PLUS_CIRCLE);
addStudentBtn.setStyleName(ValoTheme.BUTTON_FRIENDLY);
addStudentBtn.setWidth(“100px”);
grid.setStyleName(“test”);

TextField firstNameField = new TextField();
TextField lastNameField = new TextField();
TextField emailField = new TextField();

// ComboBox gender =
// new ComboBox(“Gender”);
// gender.setItems(“Male”, “Female”, “Others”);

DateField dob = new DateField();

// try {
// java.util.Date d = new
// SimpleDateFormat(“dd-MM-yyyy”).parse(stud.getBirthDate().toString());
// } catch (ParseException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }

// DateTimeFormatter formatter =
// DateTimeFormatter.ofPattern(“dd-MM-yyyy”);
// LocalDateTime dateTime = LocalDateTime.of(1986, Month.APRIL, 8, 12,
// 30);
// String formattedDateTime = dateTime.format(formatter);

Binder binder = grid.getEditor().getBinder();
binder.forField(firstNameField)
.withValidator(firstName → firstName.length() >= 3,
“First Name must contain at least three characters”)
.bind(Student::getFirstName, Student::setFirstName);
binder.forField(lastNameField).bind(Student::getLastName, Student::setLastName);
binder.forField(emailField).withValidator(new EmailValidator(“This doesn’t look like a valid email address”))
.bind(Student::getEmail, Student::setEmail);
dob.setDateFormat(“dd-MM-yyyy”);
binder.forField(dob).bind(Student::getBirthDate, Student::setBirthDate);

List students = StudentService.getStudentDetail();

// grid.setSelectionMode(SelectionMode.MULTI);

grid.setSelectionMode(SelectionMode.SINGLE);

grid.asSingleSelect().addValueChangeListener(event → {
if (event.getValue() == null)
delete.setVisible(false);
else
delete.setVisible(true);
});

grid.setItems(students);
// grid.removeColumn(“id”);
//grid.removeColumn(“birthDate”);
// DecimalFormat df = new DecimalFormat(“STU-#”);

grid.getColumn(“id”).setStyleGenerator(id → “align-right”).setWidth(80.0);
grid.getColumn(“firstName”).setEditorComponent(firstNameField).setExpandRatio(1);
grid.getColumn(“lastName”).setEditorComponent(lastNameField).setExpandRatio(1);
grid.getColumn(“email”).setEditorComponent(emailField).setExpandRatio(1);
grid.getColumn(“birthDate”).setEditorComponent(dob).setExpandRatio(1);

// Column bornColumn = grid.addColumn(“birthDate”);
// bornColumn.setRenderer(new DateRenderer(“dd-MM-yyyy”,getLocale()));
// new DateRenderer(“%1$tB %1$te,%1$tY”,Locale.ENGLISH)

grid.getEditor().setEnabled(true);

layout.addComponent(grid);
grid.setColumns(“id”, “firstName”,“lastName”, “email”, “birthDate”);
grid.getColumns().stream().forEach(column → column.setHidable(true));
grid.setFrozenColumnCount(1);

// ComboBox comboBox = new ComboBox<>();
// comboBox.setItems(StudentService.getStudentDetail());
// comboBox.setItemCaptionGenerator(s → s.getFirstName() + " " +
// s.getLastName());

addStudentBtn.addClickListener(e → refresh(grid, new Student()));

grid.getEditor().addSaveListener(e → {
StudentService.insertUpdate(e.getBean());
ListDataProvider dataProvider = (ListDataProvider) grid.getDataProvider();
dataProvider.refreshItem(e.getBean());
});

grid.getEditor().addCancelListener(e → {
// ListDataProvider dataProvider =
// (ListDataProvider) grid.getDataProvider();
// int id = grid.getSelectedItems().isEmpty();
// if (grid.getSelectedItems().iterator().next().getId()!=0)
grid.getDataProvider().refreshAll();
//grid.getSelectedItems().clear();
grid.clearSortOrder();
});

delete.addClickListener(e → {
int id = grid.getSelectedItems().iterator().next().getId();
StudentService.deleteStudent(id);
grid.setItems(students);
// ListDataProvider dataProvider = (ListDataProvider) grid.getDataProvider();
grid.getDataProvider().refreshAll();
// dataProvider.refreshAll();

grid.clearSortOrder();
});

HorizontalLayout toolbar = new HorizontalLayout(addStudentBtn, filtering, delete);

layout.addComponents(toolbar, grid);
grid.setSizeFull();
grid.setHeightByRows(10.0);
layout.setSizeFull();
layout.setExpandRatio(grid, 1.0f);
setContent(layout);
}

private void refresh(Grid studentGrid, Student student) {

ListDataProvider dataProvider = (ListDataProvider) studentGrid.getDataProvider();
List students = (List) dataProvider.getItems();
students.add(student);
dataProvider.refreshAll();
}

private void onNameFilterTextChange(HasValue.ValueChangeEvent event) {
ListDataProvider dataProvider = (ListDataProvider) grid.getDataProvider();
dataProvider.setFilter(Student::getFirstName, e → caseInsensitiveContains(e, event.getValue()));
}

private Boolean caseInsensitiveContains(String where, String what) {
return where.toLowerCase().contains(what.toLowerCase());
}

@WebServlet(urlPatterns = “/*”, name = “MyUIServlet”, asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = true)
public static class MyUIServlet extends VaadinServlet {

private static final long serialVersionUID = 1L;
}
}


Student.java


package com.student.studentgrid;

import java.time.LocalDate;

public class Student {

private int id;
private String firstName;
private String lastName;
//private Gender gender;
private LocalDate birthDate;
private String email;

public Student() {
}

public Student(String firstName, String lastName, String email) {

this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}

public Student(int id, String firstName, String lastName, String email, LocalDate birthDate) {
this(firstName, lastName, email);
this.id = id;
this.birthDate = birthDate;
}

public int getId() {
return id;
}

public void setId(int id) {
if (id < 1) {
throw new RuntimeException(“Entered ID cannot be null or empty”);
}
this.id = id;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
if ((email != null) && (email.trim().length() == 0)) {
throw new RuntimeException(“Entered Email_ID cannot be null or empty”);
}
if ((email != null) && (email.length() > 64)) {
throw new RuntimeException(“Entered Email_ID cannot be null more than 64 characters”);
}
this.email = email;
}

public LocalDate getBirthDate() {
return birthDate;
}

public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}

// public Gender getGender() {
// return gender;
// }
//
// public void setGender(Gender gender) {
// this.gender = gender;
// }

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
if (((lastName != null) && (lastName.trim().length() == 0))||(lastName.length() > 40)) {
throw new RuntimeException(“Entered Last Name cannot be null or empty and should not be more than 25 characters”);
}
// if ((lastName != null) && (lastName.length() > 40)) {
// throw new RuntimeException(“Entered Last Name cannot be null more than 25 characters”);
// }
this.lastName = lastName;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
if ((firstName != null) && (firstName.trim().length() == 0)) {
throw new RuntimeException("Entered First Name cannot be null or empty ");
}
if ((firstName != null) && (firstName.length() > 40)) {
throw new RuntimeException(“Entered First Name cannot be null more than 25 characters”);
}
this.firstName = firstName;
}

public enum Gender {
M, F, O
}
}


StudentService.java


package com.student.studentgrid;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.student.service.DBS;

public class StudentService {

private static final String SQL_SELECT_STUDENT = " SELECT id, FirstName, LastName, Email, DOB FROM studentdetails";
private static final String SQL_INSERT_STUDENT = “INSERT INTO studentdetails (FirstName,LastName,Email,DO [emoticon]
VALUES (?,?,?,?);”;
private static final String SQL_DELETE_STUDENT = “DELETE from studentdetails WHERE ID=?”;
private static final String SQL_UPDATE_STUDENT = “UPDATE studentdetails SET FirstName=?, LastName=?, Email= ?, DOB = ? WHERE id=?”;
private static final String SQL_CHECK_ID_EXISTENCE = " SELECT id FROM studentdetails where id = ?";
private static DBS dataService = DBS.getInstance();
//private static Connection con;
//private static PreparedStatement ps;
//private static ResultSet rs;

public static List getStudentDetail() {

Connection con = dataService.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;

List studentList = new ArrayList<>();
try {
ps = con.prepareStatement(SQL_SELECT_STUDENT);
rs = ps.executeQuery();
while (rs.next()) {
Student student = new Student(rs.getInt(“ID”), rs.getString(“FirstName”), rs.getString(“LastName”),
rs.getString(“Email”), rs.getDate(“DOB”).toLocalDate());
studentList.add(student);
}
} catch (Throwable th) {
throw new RuntimeException(“Problem in retrieving student data”, th);
} finally {
dataService.closeResources(rs, ps, con);
}
return studentList;
}

public static void insertStudent(Student student) {

PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = dataService.getConnection().prepareStatement(SQL_INSERT_STUDENT, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, student.getFirstName());
ps.setString(2, student.getLastName());
ps.setString(3, student.getEmail());
java.sql.Date date = Date.valueOf(student.getBirthDate());
ps.setDate(4, date);
ps.executeUpdate();

rs = ps.getGeneratedKeys();
if (rs.next()) {
student.setId(rs.getInt(1));
}
} catch (Throwable th) {
throw new RuntimeException(“Problem for inserting student for” + student.getId(), th);
}
}

public static void deleteStudent(int id) {

Connection con = dataService.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;

try {
ps = con.prepareStatement(SQL_DELETE_STUDENT);
ps.setInt(1, id);

ps.executeUpdate();
} catch (Throwable th) {
throw new RuntimeException("Problem in Deleting the Student Detail for " + id, th);
} finally {
dataService.closeResources(rs, ps, con);
}
}

public static void updateStudent(Student student) {

PreparedStatement ps = null;
try {
ps = dataService.getConnection().prepareStatement(SQL_UPDATE_STUDENT);
ps.setString(1, student.getFirstName());
ps.setString(2, student.getLastName());
ps.setString(3, student.getEmail());
java.sql.Date date = Date.valueOf(student.getBirthDate());
ps.setDate(4, date);
ps.setInt(5, student.getId());
ps.executeUpdate();
} catch (Throwable th) {
throw new RuntimeException("Problem in update the Student Detail for " + student.getId(), th);
}
}

public static void insertUpdate(Student student) {
Connection con = dataService.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {

ps = con.prepareStatement(SQL_CHECK_ID_EXISTENCE);
ps.setInt(1, student.getId());
rs = ps.executeQuery();
if (rs.next()) {
StudentService.updateStudent(student);
} else {
StudentService.insertStudent(student);
}
} catch (Throwable th) {
throw new RuntimeException("Problem in update the Student Detail for " + student.getId(), th);
} finally {
dataService.closeResources(rs, ps, con);
}
}

}

Dear Neeraj,

can we please discuss one issue at a time?
I know from a customer project that date format is handled perfectly fine in this Add-On:
https://vaadin.com/directory#!addon/gridutil

In the code you provide there is no DateRenderer in effect, so can you please provide an exact step-by-step walkthrough to reproduce the problem?

Together with an expected-vs-witnessed problem description?

This would help a lot. Thanks in advance!

Best Regards,
–Enver

Sure Enver, I will come up with that very soon.