Reputation: 8404
I have a shiny dashboard below in which I want to be able to select multiple rows from the datatable and when the user selects a row and presses the actionbutton the relative mpg
cells to be displayed in the box. Now I can store only my first selection.
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(
sidebarMenu()
),
dashboardBody(
uiOutput("jobs")
)
)
server <- function(input, output, session) {
# helper for debugging
observeEvent(input$action, {
print(mtcars)
})
# graph
# jobs UI
output$jobs <- renderUI({
list(
fluidRow(
uiOutput("job_selected")),
fluidRow(
DTOutput("jobslist")))
})
output$jobslist <- renderDT({
if (!is.null(mtcars)) {
r <- mtcars %>%
select(mpg,cyl,disp,hp,drat,wt)
datatable(r,
# escape = F,
selection = "multiple",
options = list(
columnDefs = list(list(searchable = F, targets = c(2, 5)))),
filter = "top")
}
})
output$job_selected <- renderUI({
req(input$jobslist_rows_selected)
list(
box(width = 6,
mtcars %>%
filter(row_number() %in% input$jobslist_rows_selected) %>%
pull(mpg),
tags$br(),
actionButton("assignCB", "assigned selected to CB")
)
)
})
}
shinyApp(ui, server)
Upvotes: 1
Views: 315
Reputation: 3438
I think you're complicating things a little bit here. You don't need renderUI
/uiOutput
. I would just define a box, the action button and the datatable outputs; use an eventReactive
tied to the button to only get the selected rows (and generate the text from them) when the button is clicked; and renderText
tied to the eventReactive
variable.
library(shiny)
library(shinydashboard)
library(DT)
library(dplyr)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
box(
title='selected',
width = 6,
solidHeader = TRUE,
status = "primary",
textOutput('selected_rows')),
actionButton("get_selected_rows", 'Get selected rows'),
DTOutput("my_dt"))
)
server <- function(input, output, session) {
# show DT
output$my_dt <- renderDT({
mtcars %>%
select(mpg, cyl, disp, hp, drat, wt) %>%
datatable(
selection = "multiple",
options = list(
columnDefs = list(list(searchable = F, targets = c(2, 5)))),
filter = "top")
})
# store data as text variable
my_selected_rows <- eventReactive(input$get_selected_rows, {
rows_selected <- input$my_dt_rows_selected
selected_values <- mtcars %>%
filter(row_number() %in% rows_selected) %>%
select(mpg)
unlist(selected_values)
})
# render text variable to be used in textOutput
output$selected_rows <- renderText({
my_selected_rows()
})
}
shinyApp(ui, server)
Upvotes: 1