All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.vaadin.viritin.fields.CollectionSelect Maven / Gradle / Ivy

package org.vaadin.viritin.fields;

import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomField;
import com.vaadin.ui.ListSelect;

import java.util.Collection;
import java.util.HashSet;

/**
 * TODO improve this, just copy pasted from archived SmartFields addon.
 * 
 * @see MultiSelectTable A table based and more complete version of this.
 * 
 * @author mstahv
 * @param  the type of the value for this select
 */
@Deprecated
public class CollectionSelect extends CustomField> {

	private ListSelect select = new ListSelect() {

		@SuppressWarnings("unchecked")
        @Override
		public String getItemCaption(Object option) {
			if (captionGenerator != null) {
				return captionGenerator.getCaption((T) option);
			}
			return super.getItemCaption(option);
		};
	};
	private CaptionGenerator captionGenerator;

	@Override
	protected Component initContent() {
		return select;
	}

	public CollectionSelect() {
		select.setMultiSelect(true);
		select.addValueChangeListener(new ValueChangeListener() {

			@Override
			public void valueChange(
					com.vaadin.data.Property.ValueChangeEvent event) {
				/*
				 * Modify the original collection to make it possible for e.g.
				 * ORM tools to optimize queries
				 */

				Collection collection = getInternalValue();
				HashSet orphaned = new HashSet<>(collection);

				@SuppressWarnings("unchecked")
				Collection newValueSet = (Collection) select.getValue();
				for (T t : newValueSet) {
					orphaned.remove(t);
					if (!collection.contains(t)) {
						collection.add(t);
					}
				}
				collection.removeAll(orphaned);
				CollectionSelect.super.setInternalValue(collection);
				fireValueChange(true);
			}
		});
	}

	public CollectionSelect(Collection options) {
		this();
		setOptions(options);
	}
	public CollectionSelect(String caption, Collection options) {
		this(caption);
		setOptions(options);
	}

	public CollectionSelect(String caption) {
		this();
		setCaption(caption);
	}

	@SuppressWarnings("deprecation")
	public void setOptions(Collection options) {
		select.setContainerDataSource(new BeanItemContainer<>(options));
	}

	@SuppressWarnings("unchecked")
	@Override
	public Class> getType() {
		try {
			return getPropertyDataSource().getType();
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	protected void setInternalValue(Collection newValue) {
		super.setInternalValue(newValue);
		select.setValue(newValue);
	}

	public CaptionGenerator getCaptionGenerator() {
		return captionGenerator;
	}

	public void setCaptionGenerator(CaptionGenerator captionGenerator) {
		this.captionGenerator = captionGenerator;
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy