Search code examples
rhtmlwidgetsrhandsontable

How can I set a single cell to `date` format using rhandsontable?


Usin the {rhandsontable} package it's possible to create a table where date columns include a dropdown for each cell, both providing a slick UI and validation of user inputs.

I want to set a single cell in a column to use this format, but this level of specificity doesn't seem possible with the package's API:

Use date formatting for a whole column

library(rhandsontable)

rhandsontable(
  data.frame(
    date = seq(as.Date("2020-01-01"), by = "days", length.out = 4)
  )
)

enter image description here

Use date formatting for a single cell

For example, the data for a whole column might be something like this:

# E.g. for the third cell in column `x`
rhandsontable(
  data.frame(
    x = c("foo", "bar", "2020/01/01")
  )
)

Unfortunately it looks like {rhandsontable} doesn't support a way to set the third cell to date format out of the box. hot_cell() exists to set single-cell properties such as comments, but can't be used to set the cell format.


Solution

  • Browsing the source code for rhandsontable() and hot_cell() I found I could achieve something like this fairly easily, although this is definitely an 'off-label' feature:

    library(rhandsontable)
    
    df <- data.frame(
      y = c("foo", "bar", "2020/01/01")
    )
    
    hot <- rhandsontable(df)
    
    hot$x$cell <- list(list(
      row = 2,
      col = 0,
      type = "date",
      correctFormat = TRUE,
      dateFormat = "MM/DD/YYYY"
    ))
    
    hot
    

    enter image description here