wicketdropdownchoice

Replace "Choose One" with another text programmatically


I need to replace the "Choose One" text in a DropDownChoice with another text programmatically. (I.e. I can't put the replacement text in a .properties file as suggested here.) How do I achieve this?

To give a little context, I have objects that looks roughly like

FruitOption
    "No fruit chosen"
    Orange
    Banana

AnimalOption
    "No animal chosen"
    Dog
    Cat

and the "No _____ chosen" string is part of the option-object and loaded from database.

I realize I could use a null object pattern, and give the null-object a special treatment in the ChoiceRenderer, but I'd prefer not to because the choice-objects are of an abstract type that's inconvenient to create a dummy-object for.


Solution

  • All of the following NULL-oriented methods are declared in: AbstractSingleSelectChoice (see the online JavaDoc ), which is the super-class of: DropDownChoice. You may define any of the related String values in your component or use a formatted message based on properties. Review the methods to understand how they work and then replace the example implementations with whatever fits your needs:

    /**
     * Returns the display value for the null value.
     * The default behavior is to look the value up by
     * using the key retrieved by calling: <code>getNullValidKey()</code>.
     *
     * @return The value to display for null
     */
    protected String getNullValidDisplayValue() {
        String option = 
                getLocalizer().getStringIgnoreSettings(getNullValidKey(), this, null, null);
        if (Strings.isEmpty(option)) {
            option = getLocalizer().getString("nullValid", this, "");
        }
        return option;
    }
    
    /**
     * Return the localization key for the nullValid value
     * 
     * @return getId() + ".nullValid"
     */
    protected String getNullValidKey() {
        return getId() + ".nullValid";
    }
    
    /**
     * Returns the display value if null is not valid but is selected.
     * The default behavior is to look the value up by using the key
     * retrieved by calling: <code>getNullKey()</code>.
     *
     * @return The value to display if null is not valid but is
     *     selected, e.g. "Choose One"
     */
    protected String getNullKeyDisplayValue() {
        String option =
                getLocalizer().getStringIgnoreSettings(getNullKey(), this, null, null);
    
        if (Strings.isEmpty(option)) {
            option = getLocalizer().getString("null", this, CHOOSE_ONE);
        }
        return option;
    }
    
    /**
     * Return the localization key for null value
     * 
     * @return getId() + ".null"
     */
    protected String getNullKey() {
        return getId() + ".null";
    }