2012-02-02 100 views
1

我在使用wicket進行本地化時遇到了一些問題。在Wicket的構造函數中調用getString()會給出錯誤

這是代碼:

private String displayString; 
private TextField<String> myTextField; 

public myPage(DomainObject domainObject){ 
    if(domainObject != null) 
     displayString = domainObject.getDisplayString(); 
    myTextField = new TextField<String>("myTextField", new PropertyModel<String>(this, "displayString")); 

    if(Strings.isEmpty(displayString)) 
     displayString = getString("mandatory"); //<- error message here 

} 

問題是調用的getString在一條錯誤消息的構造結果(」 ......這有時會導致一個無效的或沒有本地化資源返回... 「)。 我想爲TextField使用PropertyModel,因爲我不想翻譯從domainObject.getDisplayString()獲取的字符串。我不希望在TextField中所做的更改直接影響domainObject中的值。 有可能擺脫錯誤消息通過做這個代替的getString的:

if(Strings.isEmpty(displayString)) 
    displayString = new ResourceModel("mandatory").getObject(); //<- no error message 

據我瞭解,這是同樣的事情,調用的getString(你只是謬以千里的警告,但問題仍然存在) 。 我想到了一個解決辦法是這樣的:

@Override 
protected void onAfterRender() { 
    super.onAfterRender(); 
    if(Strings.isEmpty(displayString)) 
     displayString = getString("mandatory"); //<- no error message 
} 

有誰看到一個問題,這個解決方案?也許我不是在想「夠瘋狂」嗎?

回答

6

調用getString()需要組件位於組件層次結構中,在組件層次結構中它可以訪問它的父級,以便有機會回退到樹中定義的屬性或更高級別的屬性。這在組件的構造函數中是不可能的(因爲您稍後將它添加到它的父項)。 Wicket 1.5爲這些操作引入了onInitialize函數。隨着在此之前檢票版本,有效仿這種行爲的簡單方法:

在你的基礎組件和頁面定義一個非最終空方法

protected void onInitialize() {} 

,這增加了onBeforeRender方法:

protected void onBeforeRender() { 
... 
    if (!hasBeenRendered()) { 
     onInitialize(); 
    } 
... 
} 

然後你可以使用一個重寫onInitialize()方法,在你的任何組件來處理具有等到組件層次建立的東西。

+1

正如我添加到答案中的鏈接所示,onInitialize()自1.4起可用,而不是1.5。 – biziclop 2012-02-03 00:13:24

+0

@biziclop感謝您指出。我總是相信[Wicket 1.5遷移說明](https://cwiki.apache.org/WICKET/migration-to-wicket-15.html#MigrationtoWicket1.5-ComponentInitializationComponent%2523onInitialize)關於此... – Nicktar 2012-02-03 11:18:34

2

什麼可重複使用的行爲:

public class MandatoryBehavior extends AbstractBehavior { 
    public void onComponentTag(Component component, ComponentTag tag) { 
    if (((AbstractTextComponent)component).isRequired() && Strings.isEmpty(tag.get("value"))) { 
     tag.put("value", component.getString("mandatory")); 
    } 
    } 
} 

你必須在驗證雖然檢查提交的值。

HTML5佔位符更好。