the reason i suggested adding both is that the builtin textfiend and checkbox components check the input type of the markup they are attached to, so textfield can only be attached to type="text" and checkbox to type="checkbox". since you are not using the builtin components it looks like, you can safely do what you are.
-igor On Sat, Apr 4, 2009 at 6:49 PM, Ian MacLarty <[email protected]> wrote: > On Sat, Apr 4, 2009 at 2:16 PM, Igor Vaynberg <[email protected]> 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: [email protected] > For additional commands, e-mail: [email protected] > > --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
