确定在Vaadin中修改了哪些文本字段

时间:2013-07-15 21:29:52

标签: java javabeans textfield vaadin

我有一个数据源为BeanItemContainer的表。

当用户选择表格中的行时,相应的列会填充一组TextFields,以便用户可以编辑信息。我想要做的是找出一种干净的方法,以便在用户点击保存)时识别哪些Fields被编辑,以便我跟踪一下用户,以便我只保存必要的)。

我已经看到我可以使用isModified()查看Field是否已从之前的值更改,但是每TextField调用此值似乎很多(还{当我在文本字段中调用它时,{1}}似乎不起作用)。所以我基本上都在寻找更好的方法来检查字段是否已被修改。

谢谢

2 个答案:

答案 0 :(得分:0)

创建TextField时,将当前的Property值(String)放在TextField:

tf.setData(property.getValue())

当用户点击“保存”时,您可以比较两个值(当前和已保存的值)。

答案 1 :(得分:0)

使用BeanItem属性。您必须自己比较值,但是您在每个属性的循环中进行比较(请参阅源代码中的方法“之间”)。您只需要可以用作BeanItem的数据类,或者是BeanItem本身。在UI中,您需要具有原始数据的对象和具有更改的原始数据的对象。这是我用来提取两个版本数据之间的变化的类:

public class Diff implements Iterable<DiffEntry>{

public static class DiffEntry{
    public final Object propertyId;
    public final Object oldValue;
    public final Object newValue;

    public DiffEntry(Object propertyId, Object oldValue, Object newValue) {
        super();
        this.propertyId = propertyId;
        this.oldValue = oldValue;
        this.newValue = newValue;
    }
}

public static <T> Diff between(T oldPojo, T newPojo) {
    //HERE WE EXTRACT WHAT WAS CHANGED
    // this could also take BeanItems directly if data are BeanItems
    Diff diff = new Diff();
    BeanItem<T> oldBean = new BeanItem<T>(oldPojo);
    BeanItem<T> newBean = new BeanItem<T>(newPojo);
    for(Object propertyId : oldBean.getItemPropertyIds()) {
        Object oldValue = oldBean.getItemProperty(propertyId).getValue();
        Object newValue = newBean.getItemProperty(propertyId).getValue();
        if(oldValue == null) {
            if(newValue != null) {
                DiffEntry entry = new DiffEntry(propertyId, oldValue, newValue);
                diff.add(entry);
            }
        }
        else if(newValue == null) {
            DiffEntry entry = new DiffEntry(propertyId, oldValue, newValue);
            diff.add(entry);
        }
        else if(!oldValue.equals(newValue)) {
            DiffEntry entry = new DiffEntry(propertyId, oldValue, newValue);
            diff.add(entry);
        }
        else {
            //old and new values are equal
        }
    }
    return diff;
}

private final Map<Object, DiffEntry> entries = new HashMap<>();

public Diff() {

}

private void add(DiffEntry entry) {
    this.entries.put(entry.propertyId, entry);
}

/**
 * Returns true if this diff contains difference for specified property id
 * @param propertyId id of property we test for difference
 * @return true if this diff contains difference for specified property id
 */
public boolean contains(Object propertyId) {
    return this.entries.containsKey(propertyId);
}

/**
 * Returns true if there are no differencies
 * @return true if there are no differencies
 */
public boolean isEmpty() {
    return this.entries.isEmpty();
}

@Override
public Iterator<DiffEntry> iterator() {
    return entries.values().iterator();
}
}

在您的上下文“跟踪用户所做的更改,并且只保存必要的内容”这将完成工作,但它不会阻止处理来自UI的所有字段,因为这是在从字段中读取所有数据并存储在 newPojo 之后完成的!