简体   繁体   中英

Using action button to set value of widget in R Shiny

Essentially I have a datetime based data frame. There are some widgets that control the plots based on equipment operating. When a datetime is chosen, the plots automatically update to show the equipment operating at that point. The user can change the plots to show different equipment lineups. The idea is to have an action button to "reset" the widgets to the currently selected equipment lineup based on the datetime the user has selected. Below is my MRE.

library(shiny)
library(tidyverse)

test_data <- c(TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE)

ui <- fluidPage(
    titlePanel("Action Button Test"),
    sidebarLayout(
        sidebarPanel(
            numericInput("num", label = h3("Select Row:"), value = 4),
            actionButton("action", label = "Reset State")
        ),
        mainPanel(uiOutput('checkBox'))
    )
)

server <- function(input, output) {
    current_state <- reactive({
        test_data[input$num]
    })
    output$checkBox <- renderUI({
        checkboxInput("checkbox", label = "State", value = current_state())
    })
    observeEvent(input$action, {
        current_state <- test_data[input$num]
    })
}

shinyApp(ui = ui, server = server)

I believe I need to change the code in the observeEvent portion, but I'm open to ideas on how to better arrange this.

Lets make the checkbox be dependant on the current_state() , we can achieve that with the first observeEvent(current_state(),{... . The reset part we just update the input$num using the second observeEvent(input$action, {... and since the checkbox is already dependant on the current_state() it will auto reset also...

library(shiny)
test_data <- c(TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE)
original_state <- 4

ui <- fluidPage(
    titlePanel("Action Button Test"),
    sidebarLayout(
        sidebarPanel(
            numericInput("num", label = h3("Select Row:"), value = original_state,max = length(test_data)),
            actionButton("action", label = "Reset State")
        ),
        mainPanel(
            checkboxInput("checkbox", label = "State", value = test_data[original_state])
        )
    )
)

server <- function(input, output, session) {
    
    current_state <- reactive({
        test_data[input$num]
    })

    observeEvent(current_state(),{
        updateCheckboxInput(session, "checkbox", value = current_state())
    })
    
    observeEvent(input$action, {
        updateNumericInput(session,'num', value = original_state)
    })
}

shinyApp(ui = ui, server = server)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM