viernes, 23 de abril de 2021

42. Vaadin store additional info in a component using attributes. Grid editor disable components using the stored info in attribute

 0. Introduction

Sometimes we want to disable a component from the grid editor. If the component has information that informs that it should be disabled, then most of the work is done

Most of the code is based on Vaadin grid editor tutorial

Let's see how

  • create a new attribute in the component and store info in this attribute 
  • after invoking "grid.getEditor().editItem(record);" locate the component, read the attribute and if the attribute matches some conditions, then disable the component



1. Let's create the grid and assign a list of records

Grid<Person> grid = new Grid<>();
List<Person> persons = getItems();
grid.setItems(persons);


2. Create a column for the desired field (for instance firstName)

Grid.Column<Person> firstNameColumn =
    grid.addColumn(Person::getFirstName)
       .setHeader("First Name");


3. Create a binder for the Person class

Binder<Person> binder = new Binder<>(Person.class);


4. Extract the grid editor and set this binder

Editor<Person> editor = grid.getEditor();
editor.setBinder(binder);
editor.setBuffered(true);


5. Create a component for instance a TexField for that field

TextField firstNameField = new TextField();


6. Bind the component to the field of the class

binder.bind(firstNameField, "firstName");


7. Optional you can create a new column for storing the buttons Save and Cancel

Grid.Column<Person> editorColumn = grid.addComponentColumn(person ->  {
    Button edit = new Button("Edit");
    edit.addClassName("edit");
    edit.addClickListener(e -> {
        editor.editItem(person);
        firstNameField.focus();
    });
    edit.setEnabled(!editor.isOpen());
    editButtons.add(edit);
    return edit;
});


8. Create a new attribute that indicates that this element cannot be enabled for instance "canenable"

firstNameField.getElement().setAttribute("canenable", "FALSE");


9. when invoking the editor, detect if this attribute is present and disable the component

grid.getEditor().editItem(event.getItem()); 
   //or grid.getEditor().editItem(aPerson)

String canEnable="TRUE";

Element elem =firstNameField.getElement();
if (elem.hasAttribute("canenable"))  
    canEnable=elem.getAttribute("caneable").trim();
if (canEnable.equalsIgnoreCase("FALSE") 
    firstNameField.setEnabled(false);
else firstNameField.setEnabled(true);



10. Now this component is disabled for editing!




No hay comentarios:

Publicar un comentario