-
-
Save bezany/c2b6302b311e7595b19a902e299945e6 to your computer and use it in GitHub Desktop.
Basic form-submission shiny app used in "Persistent data storage in shiny apps" article http://deanattali.com/blog/shiny-persistent-data-storage/ Upd: add mobgolite example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(shiny) | |
library(mongolite) | |
# Define the fields we want to save from the form | |
fields <- c("name", "used_shiny", "r_num_years") | |
# Save a response | |
# ---- This is one of the two functions we will change for every storage type ---- | |
saveData <- function(data) { | |
data <- as.data.frame(t(data)) | |
if (exists("responses")) { | |
responses <<- rbind(responses, data) | |
} else { | |
responses <<- data | |
} | |
} | |
saveDataMongo <- function(data) { | |
data <- as.data.frame(t(data)) | |
con <- mongo("storage") | |
#con$insert(list(userId=10, objectname="testForExample", dataFrame=data)) | |
con$update(query = paste0('{"userId": 10, "objectName": "testForExample" }'), | |
update = paste0('{ "$set" : { "dataFrame" : ', jsonlite::toJSON(data),'} }'), upsert = TRUE) | |
} | |
# Load all previous responses | |
# ---- This is one of the two functions we will change for every storage type ---- | |
loadData <- function() { | |
if (exists("responses")) { | |
responses | |
} | |
} | |
loadDataMongo <- function() { | |
con <- mongo("storage"); | |
res <- con$find(query = paste0('{"userId": 10, "objectName": "testForExample" }')); | |
if (nrow(res) <= 0) { | |
return (NULL); | |
} | |
return(res[1,]$dataFrame[[1]]); | |
} | |
options(shiny.reactlog=TRUE) | |
# Shiny app with 3 fields that the user can submit data for | |
shinyApp( | |
ui = fluidPage( | |
DT::dataTableOutput("responses", width = 300), tags$hr(), | |
textInput("name", "Name", ""), | |
checkboxInput("used_shiny", "I've built a Shiny app in R before", FALSE), | |
sliderInput("r_num_years", "Number of years using R", 0, 25, 2, ticks = FALSE), | |
actionButton("submit", "Submit") | |
), | |
server = function(input, output, session) { | |
# Whenever a field is filled, aggregate all form data | |
formData <- reactive({ | |
data <- sapply(fields, function(x) input[[x]]) | |
data | |
}) | |
# When the Submit button is clicked, save the form data | |
observeEvent(input$submit, { | |
saveDataMongo(formData()) | |
}) | |
# Show the previous responses | |
# (update with current response when Submit is clicked) | |
output$responses <- DT::renderDataTable({ | |
input$submit | |
loadDataMongo() | |
}) | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment