shiny 使用 reactable 實(shí)現(xiàn)信息增刪改查

效果預(yù)覽:

封面.png

本文介紹了 shiny 如何實(shí)現(xiàn)信息的增刪改查,并將數(shù)據(jù)持久化到 SQLite 數(shù)據(jù)庫中儡司。

首先在 SQLite 數(shù)據(jù)庫中新建表 users几苍,表結(jié)構(gòu)如下构订。設(shè)置 id 為主鍵并自動(dòng)遞增。

字段 類型 是否允許空
id INTEGER 主鍵非空摸航,自動(dòng)遞增
username TEXT
age TEXT
birthday TEXT
address TEXT

新增信息

  1. UI 設(shè)計(jì)
新增信息UI設(shè)計(jì).png
  1. 實(shí)現(xiàn)
  observeEvent(input$adduser, {
    showModal(modalDialog(
      title = "新建用戶",
      size = "m",
      fluidPage(
        fluidRow(
          column(width = 12, textInput(inputId = "username", label = "姓名"))
        ),
        fluidRow(
          column(width = 12, textInput(inputId = "age", label = "年齡"))
        ),
        fluidRow(
          column(width = 12, dateInput(inputId = "birthday", label = "出生日期"))
        ),
        fluidRow(
          column(width = 12, textInput(inputId = "address", label = "地址"))
        )
      ),
      easyClose = FALSE,
      fade = FALSE,
      footer = tagList(
        actionButton(inputId = "useradd_confirm", label = "確認(rèn)"),
        modalButton(label = "取消")
      )
    ))
  })
  
  observeEvent(input$useradd_confirm, {
    con <-  RSQLite::dbConnect(RSQLite::SQLite(), "./data/users.db")
    tryCatch({
      addusersql <- paste0("INSERT INTO users (username, age, birthday, address) VALUES ", "('", 
                           input$username, "', '", 
                           input$age, "', '", 
                           input$birthday, "', '", 
                           input$address, "')")
      RSQLite::dbExecute(con, addusersql)
      # refresh table instance
      user_data <<- user_base()
      
      output$user_table <- renderReactable({
        # reactable中文
        options(reactable.language = reactableLang(
          pageSizeOptions = "\u663e\u793a {rows}",
          pageInfo = "{rowStart} \u81f3 {rowEnd} \u9879\u7ed3\u679c,\u5171 {rows} \u9879",
          pagePrevious = "\u4e0a\u9875",
          pageNext = "\u4e0b\u9875"
        ))
        reactable(data = user_data[c("username", "age", "birthday", "address")],
                  bordered = TRUE,
                  striped = TRUE,
                  highlight = TRUE,
                  filterable = TRUE,
                  defaultPageSize = 5,
                  showPageSizeOptions = TRUE,
                  selection = "multiple",
                  onClick = "select",
                  defaultColDef = colDef(
                    align = "left",
                    minWidth = 50
                  ),
                  columns = list(
                    .selection = colDef(
                      width = 80,
                      style = list(cursor = "pointer"),
                      headerStyle = list(cursor = "pointer")
                    ),
                    address = colDef(minWidth = 140)  # overrides the default
                  )
        )
      })
      toastr_success(title = "保存成功", message = "")
      removeModal()
    },
    warning = function(w) {
      toastr_warning("保存失敗", message = w)
    },
    error = function(e) {
      toastr_error("保存失敗", message = e)
    },
    finally = {
      RSQLite::dbDisconnect(con)
    })
  })

刪除信息

  1. UI 設(shè)計(jì)
  • 允許同時(shí)刪除多個(gè) item;
  • 當(dāng)未勾選任何信息時(shí),刪除按鈕為禁用樣式洪规;
刪除信息UI設(shè)計(jì).png
  1. 實(shí)現(xiàn)
  # 刪除
  output$deleteuser <- renderUI({
    if (length(selected()) > 0) {
      actionButton(inputId = "deleteuser", label = "刪除", icon = icon("trash-alt"), 
                   style = "background-color: #DC3545; 
                            color: #ffffff; 
                            border: none; 
                            margin-left: 15px; 
                            margin-bottom: 15px")
    } else {
      shinyjs::disabled(actionButton(inputId = "deleteuser", label = "刪除", icon = icon("trash-alt"), 
                                     style = "background-color: #DC3545; 
                                              color: #ffffff; 
                                              border: none; 
                                              margin-left: 15px; 
                                              margin-bottom: 15px"))
    }
  })
  
  observeEvent(input$deleteuser, {
    showModal(modalDialog(
      title = "刪除用戶",
      size = "m",
      fluidPage(
        div("確定刪除用戶 ", 
            span(paste(user_data[selected(), "username"], collapse = ", "), 
                 style="padding: .2em .2em; 
                        margin:0; 
                        font-size:85%; 
                        background-color:rgb(175,184,193,20%); 
                        color:#DC3545; 
                        border-radius:2px;"), 
            " 嗎 ?")
      ),
      easyClose = FALSE,
      fade = FALSE,
      footer = tagList(
        actionButton(inputId = "userdelete_confirm", label = "確認(rèn)"),
        modalButton(label = "取消")
      )
    ))
  })
  
  observeEvent(input$userdelete_confirm, {
    con <-  RSQLite::dbConnect(RSQLite::SQLite(), "./data/users.db")
    tryCatch({
      deleteSql <- paste0("DELETE FROM users WHERE id=", "'", user_data[selected(), "id"], "'")
      for (sql in deleteSql) {
        RSQLite::dbExecute(con, sql)
      }
      # refresh table instance
      user_data <<- user_base()
      
      output$user_table <- renderReactable({
        options(reactable.language = reactableLang(
          pageSizeOptions = "\u663e\u793a {rows}",
          pageInfo = "{rowStart} \u81f3 {rowEnd} \u9879\u7ed3\u679c,\u5171 {rows} \u9879",
          pagePrevious = "\u4e0a\u9875",
          pageNext = "\u4e0b\u9875"
        ))
        reactable(data = user_data[c("username", "age", "birthday", "address")],
                  bordered = TRUE,
                  striped = TRUE,
                  highlight = TRUE,
                  filterable = TRUE,
                  defaultPageSize = 5,
                  showPageSizeOptions = TRUE,
                  selection = "multiple",
                  onClick = "select",
                  defaultColDef = colDef(
                    align = "left",
                    minWidth = 50
                  ),
                  columns = list(
                    .selection = colDef(
                      width = 80,
                      style = list(cursor = "pointer"),
                      headerStyle = list(cursor = "pointer")
                    ),
                    address = colDef(minWidth = 140)  # overrides the default
                  )
        )
      })
      toastr_success(title = "刪除成功", message = "")
      removeModal()
    },
    warning = function(w) {
      toastr_warning(title = "刪除失敗", message = w)
    },
    error = function(e) {
      toastr_error(title = "刪除失敗", message = e)
    },
    finally = {
      RSQLite::dbDisconnect(con)
    })
  })
}

修改信息

  1. UI 設(shè)計(jì)
  • 復(fù)用新增信息的 UI
  • 當(dāng) 未勾選任何 item勾選 item 數(shù)量 > 1 時(shí),編輯按鈕為禁用狀態(tài)循捺;
  1. 實(shí)現(xiàn)
  # 編輯
  output$edituser <- renderUI({
    # 只有選擇一項(xiàng)時(shí)可以編輯
    if (length(selected()) == 1) {
      actionButton(inputId = "edituser", label = "編輯", icon = icon("edit"),
                   style = "background-color: #007BFF; 
                            color: #ffffff; 
                            border: none; 
                            margin-left: 15px; 
                            margin-bottom: 15px")

    } else {
      shinyjs::disabled(actionButton(inputId = "edituser", label = "編輯", icon = icon("edit"),
                                     style = "background-color: #007BFF; 
                                              color: #ffffff; 
                                              border: none; 
                                              margin-left: 15px; 
                                              margin-bottom: 15px"))
    }
  })
  
  observeEvent(input$edituser, {
    showModal(modalDialog(
      title = "修改信息",
      size = "m",
      fluidPage(
        fluidRow(
          column(width = 12, 
                 textInput(inputId = "username_new", label = "姓名", 
                           value = user_data[selected(), "username"]))
        ),
        fluidRow(
          column(width = 12, 
                 textInput(inputId = "age_new", label = "年齡", 
                           value = user_data[selected(), "age"]))
        ),
        fluidRow(
          column(width = 12, 
                 dateInput(inputId = "birthday_new", label = "出生日期", 
                           value = user_data[selected(), "birthday"]))
        ),
        fluidRow(
          column(width = 12, 
                 textInput(inputId = "address_new", label = "地址", 
                           value = user_data[selected(), "address"]))
        )
      ),
      easyClose = FALSE,
      fade = FALSE,
      footer = tagList(
        actionButton(inputId = "useredit_confirm", label = "確認(rèn)"),
        modalButton(label = "取消")
      )
    ))
  })
  
  observeEvent(input$useredit_confirm, {
    # 更新用戶信息
    con <-  RSQLite::dbConnect(RSQLite::SQLite(), "./data/users.db")
    tryCatch({
      edit_standard_user_sql <- paste0("UPDATE users set username=", "'", input$username_new, "'", 
                                       ", age=", "'", input$age_new, "'", 
                                       ", birthday=", "'", input$birthday_new, "'", 
                                       ", address=", "'", input$address_new, "'",
                                       " WHERE id=", "'", user_data[selected(), "id"], "'")
      RSQLite::dbExecute(con, edit_standard_user_sql)
      # refresh table instance
      user_data <<- user_base()
      
      output$user_table <- renderReactable({
        options(reactable.language = reactableLang(
          pageSizeOptions = "\u663e\u793a {rows}",
          pageInfo = "{rowStart} \u81f3 {rowEnd} \u9879\u7ed3\u679c,\u5171 {rows} \u9879",
          pagePrevious = "\u4e0a\u9875",
          pageNext = "\u4e0b\u9875"
        ))
        reactable(data = user_data[c("username", "age", "birthday", "address")],
                  bordered = TRUE,
                  striped = TRUE,
                  highlight = TRUE,
                  filterable = TRUE,
                  defaultPageSize = 5,
                  showPageSizeOptions = TRUE,
                  selection = "multiple",
                  onClick = "select",
                  defaultColDef = colDef(
                    align = "left",
                    minWidth = 50
                  ),
                  columns = list(
                    .selection = colDef(
                      width = 80,
                      style = list(cursor = "pointer"),
                      headerStyle = list(cursor = "pointer")
                    ),
                    address = colDef(minWidth = 140)  # overrides the default
                  )
        )
      })
      toastr_success(title = "修改成功", message = "")
      removeModal()
    },
    warning = function(w) {
      toastr_warning(title = "修改失敗", message = w)
    },
    error = function(e) {
      toastr_error(title = "修改失敗", message = e)
    },
    finally = {
      RSQLite::dbDisconnect(con)
    })
  })

查找信息

reactable 中設(shè)置 filterable = TRUE 即可實(shí)現(xiàn)信息過濾查找的效果斩例;

信息查找.gif

源代碼

完整代碼詳見 https://github.com/redburning/reactable

參考

https://github.com/glin/reactable

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市从橘,隨后出現(xiàn)的幾起案子念赶,更是在濱河造成了極大的恐慌础钠,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,734評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件晶乔,死亡現(xiàn)場(chǎng)離奇詭異珍坊,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)正罢,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門阵漏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人翻具,你說我怎么就攤上這事履怯。” “怎么了裆泳?”我有些...
    開封第一講書人閱讀 164,133評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵叹洲,是天一觀的道長。 經(jīng)常有香客問我工禾,道長运提,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,532評(píng)論 1 293
  • 正文 為了忘掉前任闻葵,我火速辦了婚禮民泵,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘槽畔。我一直安慰自己栈妆,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評(píng)論 6 392
  • 文/花漫 我一把揭開白布厢钧。 她就那樣靜靜地躺著鳞尔,像睡著了一般。 火紅的嫁衣襯著肌膚如雪早直。 梳的紋絲不亂的頭發(fā)上寥假,一...
    開封第一講書人閱讀 51,462評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音霞扬,去河邊找鬼昧旨。 笑死,一個(gè)胖子當(dāng)著我的面吹牛祥得,可吹牛的內(nèi)容都是我干的兔沃。 我是一名探鬼主播,決...
    沈念sama閱讀 40,262評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼级及,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼乒疏!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起饮焦,我...
    開封第一講書人閱讀 39,153評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤怕吴,失蹤者是張志新(化名)和其女友劉穎窍侧,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體转绷,經(jīng)...
    沈念sama閱讀 45,587評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡伟件,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了议经。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片斧账。...
    茶點(diǎn)故事閱讀 39,919評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖煞肾,靈堂內(nèi)的尸體忽然破棺而出咧织,到底是詐尸還是另有隱情,我是刑警寧澤籍救,帶...
    沈念sama閱讀 35,635評(píng)論 5 345
  • 正文 年R本政府宣布习绢,位于F島的核電站,受9級(jí)特大地震影響蝙昙,放射性物質(zhì)發(fā)生泄漏闪萄。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評(píng)論 3 329
  • 文/蒙蒙 一奇颠、第九天 我趴在偏房一處隱蔽的房頂上張望败去。 院中可真熱鬧,春花似錦大刊、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至搜锰,卻和暖如春伴郁,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背蛋叼。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評(píng)論 1 269
  • 我被黑心中介騙來泰國打工焊傅, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人狈涮。 一個(gè)月前我還...
    沈念sama閱讀 48,048評(píng)論 3 370
  • 正文 我出身青樓狐胎,卻偏偏與公主長得像,于是被迫代替她去往敵國和親歌馍。 傳聞我的和親對(duì)象是個(gè)殘疾皇子握巢,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容