简体   繁体   中英

R Shiny SweetAlert - Display alert depending on user input

I would like to send a SweetAlert to the app user depending on correct password input and file upload.

My app asks a user to upload a password protected Excel file using the fileInput widget and accepts a password using the passwordInput widget:

  # file select
  output$file_select <- renderUI({
    fileInput("file_select","Import File:",buttonLabel = "Select",
              multiple = FALSE, accept = ".xlsx",placeholder = "No file selected")
  })
  # password input
  output$pword_input <-renderUI({
    passwordInput("pword_input","Password:", "", placeholder = "Enter Excel password")
  })

Reading of the Excel sheet is handled by excel.link and creates a reactive object called raw.data() :

  raw.data <- reactive({
    # Read Excel file
    data_file <- input$file_select
    df <- xl.read.file(data_file$datapath,
                       password =  input$pword_input)
   return(df)
})

Documentation for sendSweetAlert only seems to provide examples for sending an alert on action button press. However, I would like the observeEvent to look for correct password input.

I cannot store the password within the app and so I have currently set the observeEvent that triggers the SweetAlert to look for the creation of the reactive object raw.data() as an indicator that the correct password has been input:

  observeEvent(raw.data(), {
    sendSweetAlert(
      session = session,
      title = "Password Accepted",
      type = "success"
    )
  })

This functions, to a certain extent. If the correct password is input then the SweetAlert is displayed once the reactive object is created as desired. However, input of incorrect password crashes the app.

I hoped someone could help with the correct way to set this up please. I imagine my error is in the use of the observeEvent? However, without storing the password, i'm not sure how else to achieve my aim.

Thanks in advance

xl.read.file throws an error if the password is not correct. So you can try something like that (not tested):

raw.data <- reactive({
    # Read Excel file
    data_file <- input$file_select
    df <- try(xl.read.file(data_file$datapath,
                           password = input$pword_input))
   return(df)
})

observeEvent(raw.data(), {
  if(inherits(raw.data(), "try-error")) {
    sendSweetAlert(
      session = session,
      title = "Wrong password",
      type = "error"
    )
  } else {
    sendSweetAlert(
      session = session,
      title = "Password Accepted",
      type = "success"
    )
  }
})

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