问题
I'd like to apply color highlighting for a entire row depending on a value and retain check boxes functionality of rhandsontable. In the simple example below, I'd like row 3 to be pink and row 4 to be green.
library(rhandsontable)
DF = data.frame( bool = TRUE,val = 1:10, big = LETTERS[1:10],
small = letters[1:10],
stringsAsFactors = FALSE)
###Checkboxes not Present/Entire row not highlighted
rhandsontable(DF, readOnly = FALSE, width = 750, height = 300) %>%
hot_cols(renderer = "
function (instance, td, row, col, prop, value, cellProperties) {
Handsontable.renderers.NumericRenderer.apply(this, arguments);
if (value == 'C') {
td.style.background = 'pink';
} else if (value == 'D') {
td.style.background = 'green';
}
}")
####Checkboxes Present
rhandsontable(DF, readOnly = FALSE, width = 750, height = 300)
回答1:
The issue is that you use a NumericRenderer which tries to convert the applied columns to numeric. My solution may not be optimal, but it does the job.
library(rhandsontable)
DF = data.frame( bool = TRUE,val = 1:10, big = LETTERS[1:10],
small = letters[1:10],
stringsAsFactors = FALSE)
# Text Renderer
text_renderer <- "
function (instance, td, row, col, prop, value, cellProperties) {
Handsontable.renderers.TextRenderer.apply(this, arguments);
# This is the column which you want to check for coloring
var col_value = instance.getData()[row][2]
if (col_value == 'C') {
td.style.background = 'pink';
} else if (col_value == 'D') {
td.style.background = 'green';
}
}"
# Renderer for the bool column
bool_renderer <- "
function (instance, td, row, col, prop, value, cellProperties) {
Handsontable.renderers.CheckboxRenderer.apply(this, arguments);
var col_value = instance.getData()[row][2]
if (col_value == 'C') {
td.style.background = 'pink';
} else if (col_value == 'D') {
td.style.background = 'green';
}
}
"
# Entire row highlighted and checkbox attribute preserved
rhandsontable(DF, readOnly = FALSE, width = 750, height = 300) %>%
hot_col(col = c(2, 3, 4), renderer = text_renderer) %>%
hot_col("bool", renderer = bool_renderer)
The trick is that you create two renderers:
- A CheckboxRenderer specifically for your bool column
- A TextRenderer for the remaining columns.
instance.getData()[row][2]
retrieves the value of the big column at row index row
. So the renderer checks for each row whether the condition in the if-statement is TRUE.
Cheers
来源:https://stackoverflow.com/questions/44813590/rhandsontable-conditional-formatting-how-to-highlight-rows-based-on-specific-at