Skip to content

Instantly share code, notes, and snippets.

@dai0304
Created October 1, 2011 05:11
Show Gist options
  • Save dai0304/1255635 to your computer and use it in GitHub Desktop.
Save dai0304/1255635 to your computer and use it in GitHub Desktop.
....
<form method="post" wicket:id="form">
<wicket:container wicket:id="p1"><div class="clearfix error">
<label for="p1" class="xlarge">label1</label>
<div class="input"><input type="text" id="p1" class="xlarge"/></div>
</div></wicket:container>
</form>
...
Form<Void> form = new Form<Void>("form");
FormComponentPanel p1 = new FormComponentPanel("p1", Model.of("label1"));
p1.addFormComponent(new TextField<String>(FormComponentPanel.FORM_COMPONENT_ID));
// p1.addFormComponent(new CheckBox(FormComponentPanel.FORM_COMPONENT_ID));
// ◆◆◆◆ 上記はinput要素のtype属性がcheckboxではないというエラーでNG ◆◆◆◆
form.add(p1);
...
<form>
<wicket:panel>
<div class="clearfix" wicket:id="container">
<label wicket:for="formComponent" for="formComponent" class="xlarge" wicket:id="formLabel">some label</label>
<div class="input">
<input type="text" id="formComponent" class="xlarge" wicket:id="formComponent"/>
</div>
</div>
</wicket:panel>
</form>
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
public class FormComponentPanel extends Panel {
public static final String FORM_COMPONENT_ID = "formComponent";
private final WebMarkupContainer container;
private FormComponent<?> formComponent;
public FormComponentPanel(String id, IModel<String> model) {
super(id);
container = new WebMarkupContainer("container");
// formComponentにエラーがある場合は、containerのclassにerrorを追加
container.add(new AttributeAppender("class", new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
if (formComponent == null) {
throw new IllegalStateException();
}
return formComponent.isValid() ? "" : " error";
}
}));
// label要素のfor属性にformComponentのidを設定
container.add(new Label("formLabel", model)
.add(new AttributeModifier("for", new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
if (formComponent == null) {
throw new IllegalStateException();
}
return formComponent.getMarkupId();
}
})));
add(container);
}
public FormComponentPanel addFormComponent(FormComponent<?> formComponent) {
if (this.formComponent != null) {
// 複数回addは禁止
throw new IllegalStateException();
}
this.formComponent = formComponent;
container.add(formComponent);
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment