On Sat, Apr 4, 2009 at 2:16 PM, Igor Vaynberg <igor.vaynb...@gmail.com> wrote:
> create a formcomponentpanel, add a checkbox and a textfield and make
> only one of them visible.
>

I think I found a more elegant (and efficient?) way to do this if I
want to cover more than 2 model classes.

Instead of adding a component for each possible class in the
constructor and setting one of them to be visible in onBeforeRender, I
add only one component in onBeforeRender (it cannot be added in the
constructor, because I don't have access to the model at that point).
Once I've added the component I set a flag so that it isn't added
twice.

This seems to work, but I just wanted to check if there are any issues
with adding the component in onBeforeRender instead of the
constructor?

Here is the code (StringField and BooleanField are FormComponentPanels
with one TextField and CheckBox respectively):

public class DynamicComponent extends FormComponentPanel {
    private FormComponent component;
    private boolean initialized = false;

    public DynamicComponent(String id) {
        super(id);
    }

    public DynamicComponent(String id, IModel model) {
        super(id, model);
    }

    @Override
    protected void convertInput() {
        setConvertedInput(component.getConvertedInput());
    }

    @Override
    protected void onBeforeRender() {
        IModel model = getModel();
        if (!initialized) {
            Class clazz;
            if (model instanceof AbstractPropertyModel) {
                // Get the type from the AbstractPropertyModel if we can,
                // since that will work even if the value is null.
                clazz = ((AbstractPropertyModel)model).getObjectClass();
            } else {
                Object modelVal = model.getObject();
                if (modelVal != null) {
                    clazz = modelVal.getClass();
                } else {
                    clazz = String.class;
                }
            }
            if (clazz.equals(String.class)) {
                component = new StringField("component", model);
            } else if (clazz.equals(Boolean.class)) {
                component = new BooleanField("component", model);
            } else {
                throw new RuntimeException("Unhandled type: " + clazz);
            }
            add(component);
            initialized = true;
        }
        super.onBeforeRender();
    }
}

Cheers,
Ian.

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscr...@wicket.apache.org
For additional commands, e-mail: users-h...@wicket.apache.org

Reply via email to