justpy-org / justpy

An object oriented high-level Python Web Framework that requires no frontend programming
https://justpy.io
Apache License 2.0
1.22k stars 96 forks source link

how to use Ag-Grid API function #321

Closed wy1189 closed 2 years ago

wy1189 commented 2 years ago

Is there any way to run API function in the start?

I hope to use API function (here sizeColumnsToFit()) in the first page, but no success. The function itself works well, but it only works when it's connected to click event. I added await grid.run_api('sizeColumnsToFit()', wp) in the main function, but it didn't work...

Here is my example.

import justpy as jp

grid_options = """
{
    rowSelection: 'multiple',
    defaultColDef: {
        filter: true,
        sortable: true,
        resizable: true,
        cellStyle: {textAlign: 'center'},
        headerClass: 'font-bold',
        sizeColumnsToFit: true
    }, 
      columnDefs: [
      {headerName: "Make", field: "make"},
      {headerName: "Model", field: "model"},
      {headerName: "Price", field: "price"}
    ],
      rowData: [
      {make: "Toyota", model: "Celica", price: 35000},
      {make: "Ford", model: "Mondeo", price: 32000},
      {make: "Porsche", model: "Boxter", price: 72000}
    ]
}
"""

def row_selected(self, msg):
    wp = msg.page
    if msg.selected:
        wp.selected_rows[msg.rowIndex] = msg.data
    else:
        wp.selected_rows.pop(msg.rowIndex)
    s = f'Selected rows {sorted(list(wp.selected_rows.keys()))}'
    for i in sorted(wp.selected_rows):
        s = f'{s}\n Row {i}  Data: {wp.selected_rows[i]}'
    if wp.selected_rows:
        wp.rows_div.text = s
    else:
        wp.rows_div.text = 'No row selected'

async def click_to_fit(self, msg):
    await self.grid.run_api('sizeColumnsToFit()', msg.page)

async def deselect_rows(self, msg):
    await self.grid.run_api('deselectAll()', msg.page)

async def grid_test():
    wp = jp.WebPage()
    wp.selected_rows = {}  # Dictionary holding selected rows
    grid = jp.AgGrid(a=wp, options=grid_options, style='height: 200px; width: 1500px; margin: 0.25em')
    grid.options.columnDefs[0].checkboxSelection = True
    grid.on('rowSelected', row_selected)
    wp.rows_div = jp.Pre(text='Data will go here when you select rows', classes='border text-lg', a=wp)
    btn_deselect = jp.Button(text='Deselect rows', classes=jp.Styles.button_simple+' m-2', a=wp, click=deselect_rows)
    btn_deselect.grid = grid
    btn_select_all = jp.Button(text='Column to Fit', classes=jp.Styles.button_simple+' m-2', a=wp, click=click_to_fit)
    btn_select_all.grid = grid
    await grid.run_api('sizeColumnsToFit()', wp)
    return wp

jp.justpy(grid_test)
elimintz commented 2 years ago

Yes, you can use the page_ready page event and run the command there: https://justpy.io/tutorial/page_events/

wy1189 commented 2 years ago

Thanks, I'll try that!