I'm creating a shiny app that will get values from a database table and update the other upon user request. The problem arises once the add button is clicked. The checkboxes hold the same value as earlier and do not get the new values from database.
ui <- fluidPage(
checkboxGroupInput("inCheckboxGroup", "Available names", td),
checkboxGroupInput("inCheckboxGroup2", "Present names",c(ch1,ch)),
actionButton("action", label = "Add")
)
td, ch1 and ch are lists gathered from the database.
z <- NULL
server <- function(input, output, session) {
# checkbox listener
observe({
x <- input$inCheckboxGroup
y <- NULL
if (is.null(x))
x <- character(0)
# Get the names for these ids
for (i in x){
y <- dbFetch(dbSendQuery(conn, paste0("--sql query--") ))
z <- c(z,y[,1])
}
# Print the names from previous block into the checkboxes
updateCheckboxGroupInput(session, "inCheckboxGroup2",
choices = c(ch1,z),
selected = z)
})
# button listener
observeEvent(input$action,{
for(i in input$inCheckboxGroup){
rs <- dbSendQuery(conn, paste0("--sql query--"))
dbFetch(rs)
}
showNotification("Row inserted")
})
}
What I tried was to create a page refresh functionality or input reset that would do the trick. But even reloading the page does nothing. What would be the best approach for this?
You need to update the check boxes once the button is pushed so the updateCheckboxGroupInput
needs to be in the observeEvent
for the action button. Below is an example of how to do so.
library(shiny)
td<-c(1,2,3)
ch1<-c(1,2,3)
ch<-c(1,2,3)
ui <- fluidPage(
checkboxGroupInput("inCheckboxGroup", "Available names", td),
checkboxGroupInput("inCheckboxGroup2", "Present names",c(ch1,ch)),
actionButton("action", label = "Add")
)
server<-function(input,output,session){
# button listener
observeEvent(input$action,{
database<-c(4,5,6)
updateCheckboxGroupInput(session,"inCheckboxGroup", choices = database)
})
}
shinyApp(ui, server)
If trying to update the values of the check boxes, do a similar command but used selected
. Also below is how to update both sets of checkboxes.
# button listener
observeEvent(input$action,{
database<-c(1,3)
updateCheckboxGroupInput(session,"inCheckboxGroup", selected=database)
#For the Second group simply call the other label
updateCheckboxGroupInput(session,"inCheckboxGroup2", selected=database)
})
}