dreamRs / shinytreeview

Hierarchical tree input for Shiny apps
GNU General Public License v3.0
41 stars 8 forks source link

Is there a way in which the menu can automatically collapse back once a country is selected? #5

Open Shelmith-Kariuki opened 2 years ago

Shelmith-Kariuki commented 2 years ago

Hi @pvictor ,

Thank you so much for this package.

Is there a way in which the menu can automatically collapse back once a country is selected?

` library(shiny) library(shinytreeview)

data("cities")

ui <- fluidPage( tags$h3("treeviewInput cities example"), treeviewInput( inputId = "tree", label = "Choose a city:", choices = make_tree( cities, c("continent", "country", "city") ), multiple = FALSE, prevent_unselect = TRUE, width = "100%" ), verbatimTextOutput(outputId = "result") )

server <- function(input, output, session) { output$result <- renderPrint({ input$tree }) }

if (interactive()) shinyApp(ui, server) `

pvictor commented 2 years ago

Hi,

You can collapse levels from your server with collapseTreeview().

There's two solutions :

collapseTreeview("tree") # "tree" is inputId of the widget
nodes <- input$tree_nodes
this_node <- nodes[nodes$text == input$tree, "parentId"]
collapseTreeview("tree", nodeId = this_node)

Here's an example:

library(shiny)
library(shinytreeview)

data("cities")

ui <- fluidPage(
  tags$h3("treeviewInput cities example"),
  treeviewInput(
    inputId = "tree",
    label = "Choose a city:",
    choices = make_tree(
      cities, c("continent", "country", "city")
    ),
    multiple = FALSE,
    prevent_unselect = TRUE,
    width = "100%"
  ),
  verbatimTextOutput(outputId = "result"),
  verbatimTextOutput(outputId = "nodes")
)

server <- function(input, output, session) {

  observeEvent(input$tree, {
    if (input$tree %in% cities$city) {
      nodes <- input$tree_nodes
      this_node <- nodes[nodes$text == input$tree, "parentId"]
      collapseTreeview("tree", nodeId = this_node)
      # or collapse all levels with:
      # collapseTreeview("tree")
    }
  })

  output$result <- renderPrint({
    input$tree
  })

  output$nodes <- renderPrint({
    input$tree_nodes
  })

}

if (interactive())
  shinyApp(ui, server)

Victor

Shelmith-Kariuki commented 2 years ago

Hi @pvictor that worked ... thank you.