NOOB - fill table from results of a service

Hi:
I’m going through the Hands-On lab but I only have the free version right now. Instead of display a Pie Chart, I figured I would fill a table with the results of the OrderService.getMechanicOrderStats call. Here is the code I wrote, based on Dynamic Entities - CUBA.Platform link:


public class MechanicBrowse extends AbstractLookup {
    @Inject
    private OrderService orderService;

    @Inject
    private Table statsTable;

    @Override
    public void init(Map<String, Object> params) {
        super.init(params);

        KeyValueCollectionDatasourceImpl ds = new DsBuilder().buildCollectionDatasource(KeyValueCollectionDatasourceImpl.class);
        ds.addProperty("mechanic").addProperty("orders");

        Map<Mechanic, Long> stats = orderService.getMechanicOrderStats();

        for (Map.Entry<Mechanic, Long> entry: stats.entrySet()) {
            KeyValueEntity entity = new KeyValueEntity();
            entity.setValue("mechanic", InstanceUtils.getInstanceName(entry.getKey()));
            entity.setValue("orders", entry.getValue());
            ds.includeItem(entity);
        }

        statsTable.setDatasource(ds);
        statsTable.setVisible(true);
    }
}

mechanic-browse.xml contains:


        <table id="statsTable"
               height="200px"
               width="100%">
            <columns>
                <column id="mechanic"/>
                <column id="orders"/>
            </columns>
            <rows/>
        </table>

The code compiles fine, but I get the following error at runtime:


GuiDevelopmentException: Table 'rows' element doesn't have 'datasource' attribute
Frame ID: workshop$Mechanic.browse
XML descriptor: com/company/workshop/gui/mechanic/mechanic-browse.xml
Table ID: statsTable

I’m setting the datasource inside the init function. Why is it not seeing it? What’s the correct way to do this?

Thanks in advance…

1 Like

Hi Eric,

Unfortunately, the table XML loader works in such a way that a datasource for the table should be specified in XML too. This is a shortcoming and probably we will fix it in the future.

For now, you have to create the table programmatically together with the datasource. For example:


Table table = componentsFactory.createComponent(Table.class);
table.setDatasource(ds);
table.setColumnCaption("mechanic", "Mechanic");
table.setColumnCaption("orders", "Orders");

table.setWidth("100%");
table.setHeight("100%");

addComponent(table);

Please also note, that in version 6.3 values in KeyValueCollectionDatasourceImpl should be of type String to be properly displayed in a table, so you need to convert orders value to string.

BTW, we significantly improved KeyValueEntity and the corresponding datasources in the upcoming version 6.4 - they can be declared in XML and load data from middleware using JPQL queries.