posit-dev / py-shiny

Shiny for Python
https://shiny.posit.co/py/
MIT License
1.1k stars 62 forks source link

example for update_cell_selection #1446

Closed maxmoro closed 4 weeks ago

maxmoro commented 4 weeks ago

Is it possibile to have an example of the update_cell_selection method? I'm trying to use it but I see no effect In this code I was tryng to set a selected row when a user clicks a button.


from palmerpenguins import load_penguins
from shiny import App, render, ui, reactive, Outputs

penguins = load_penguins()

app_ui = ui.page_fluid(
    ui.h2("Palmer Penguins"),
    ui.input_switch("sel_edit", "Edit", False),  
    ui.input_action_button('click','click'),
    ui.output_ui("rows"),
    ui.output_data_frame("penguins_df"),
)

def server(input, output, session):

    @reactive.Effect
    @reactive.event(input.sel_edit)
    def sel_edit():
        print('b')

    @render.data_frame
    def penguins_df():
        return render.DataTable(penguins, selection_mode="row",editable=False,)  

    @reactive.Effect 
    @reactive.event(input.click)
    def click():
        print('a')
        x={'type': 'row', 'rows': (4)}
        penguins_df.update_cell_selection(x)

    @render.ui
    def rows():
        rows = penguins_df.cell_selection()["rows"]  
        selected = ", ".join(str(i) for i in sorted(rows)) if rows else "None"
        return f"Rows selected: {selected}"

app = App(app_ui, server)
schloerke commented 4 weeks ago

@maxmoro Thank you for the reprex!

Your code works, just needs to add async (for click) and await the update method:

    @reactive.Effect 
    @reactive.event(input.click)
    async def click():
        print('a')
        x={'type': 'row', 'rows': (4)}
        await penguins_df.update_cell_selection(x)

Link to updated shinylive app.

https://github.com/posit-dev/py-shiny/assets/93231/4311b139-44ab-45e6-bb58-0785c17cfb49

maxmoro commented 4 weeks ago

Amazing! Thank you very much.