2012-02-02 101 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占位符更好。