javawicket

Add ExternalLink column to DefaultDataTable in Wicket


I have a DefaultDataTable to display entities and in one of its columns I'd like to have links (ExternalLink) for those entities. But doing the following does not really give me links, it shows only the link text.

This way I create the columns:

List<IColumn<Entity, String>> columns = List.of(
  new PropertyColumn<>(new Model<>("Id"), "id", "id"),
  new PropertyColumn<>(new Model<>("Name"), "name", "name"),
  new IColumn<>() {
    @Override
    public Component getHeader(String componentId) {
      return new Label(componentId, "Link");
    }
    @Override
    public String getSortProperty() {
      return null; // No sorting
    }
    @Override
    public void populateItem(Item<ICellPopulator<Entity>> cellItem, String componentId, IModel<Entity rowModel) {
      cellItem.add(new ExternalLink(componentId,
        "https://example.com/entity/" + rowModel.getObject().getExtid()),
        rowModel.getObject().getName());
    }
    @Override
    public void detach() { }
  }
);

This way the DefaultDataTable is created:

var entityDataTable = new DefaultDataTable<>("entity_data_table", columns, dataProvider, 20);
add(entityDataTable);

But in the browser it looks like the second column is just repeated as the third:

enter image description here

So how can I show a link column in a data table? Btw. I'm using Apache Wicket 9.14.


Solution

  • You need to provide markup for the cell contents. I.e. instead of adding an ExternalLink you need to add a markup provider like a Panel or a Fragment that contains the ExternalLink as a child.

    @Override
    public void populateItem(Item<ICellPopulator<Entity>> cellItem, String componentId, IModel<Entity rowModel) {
      cellItem.add(new MyPanel(componentId));
    }
    ...
    

    MyPanel.java:

    public class MyPanel extends Panel {
      public MyPanel(String id) {
        super(id);
    
        add(new ExternalLink("link",
        "https://example.com/entity/" + rowModel.getObject().getExtid()),
        rowModel.getObject().getName()));
      }
    }
    

    MyPanel.html:

    <wicket:panel><div><a wicket:id="link"></a></div></wicket:panel>