4

I have an Inline Editable Grid. I need to modify a column to display an hyperlink, which will trigger some UI action when clicked.

Thanks.

My code so far. The link in the link column renders as a regular string. I know this is because of the toString() return below, but this is where I need help. Not sure how to render it right.

linkConf = new ColumnConfig<LinkData, String>(lp.url(), 200, "URL");
...
Anchor myLink = new Anchor();
myLink.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent cEv) {
        someAction();       
    }

    private void someAction() {

    }

});


linkConf.setWidget(myLink, new SafeHtml() {
    @Override
    public String asString() {
        return toString();
    }
});
R.V.
  • 532
  • 1
  • 6
  • 21

1 Answers1

0

In one of my project I had to do the same. I'd recommend to use CellClickHandler instead of trying to catch click on the anchor.

First create more convenient handler for your click actions:

public interface CellClickAction<P> {
  void onCellClick(P proxy);
}

Use this plugin which holds mapping for every ValueProvider in the grid:

public class GridCellClickPlugin<P> implements ComponentPlugin<Grid<P>> {

  private final Map<ValueProvider<P, ?>, CellClickAction<P>> mapping;

  public GridCellClickPlugin() {
    this.mapping = new HashMap<ValueProvider<P, ?>, CellClickAction<P>>();
  }

  @Override
  public void initPlugin(final Grid<P> component) {
    component.addCellClickHandler(new CellClickHandler() {

      @Override
      public void onCellClick(CellClickEvent event) {
        if (!mapping.isEmpty()) {
          final ColumnConfig<P, ?> columnConfig = component.getColumnModel().getColumn(event.getCellIndex());
          final CellClickAction<P> action = mapping.get(columnConfig.getValueProvider());
          if (action != null) {
            final P proxy = component.getStore().get(event.getRowIndex());
            action.onCellClick(proxy);
          }
        }
      }
    });
  }
}

Register click handler for this column and init plugin:

final GridCellClickPlugin<LinkData> plugin = new GridCellClickPlugin<LinkData>();
plugin.getMapping().put(lp.url(), new CellClickAction<LinkData>() {

  @Override
  public void onCellClick(LinkData proxy) {
    //do the desired action here: redirect to some url, show pop-up window, etc
  }  
});
plugin.init(grid);

Render your text as a link:

linkConf = new ColumnConfig<LinkData, String>(lp.url(), 200, "URL");
linkConf.setCell(new AbstractCell<LinkData>() {

  @Override
  public void render(com.google.gwt.cell.client.Cell.Context context, LinkData value, SafeHtmlBuilder sb) {
    final Anchor anchor = new Anchor(value.getSomeText());
    sb.appendHtmlConstant(anchor.getElement().toString());
  }
});
Yurii Shylov
  • 1,219
  • 1
  • 10
  • 19