Skip to content

Commit

Permalink
feat: value_attr option as callable in columns
Browse files Browse the repository at this point in the history
  • Loading branch information
Kreyu committed Jun 15, 2023
1 parent a6e19c8 commit 2dde783
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
16 changes: 15 additions & 1 deletion docs/reference/columns/types/_column_options.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ $builder

### `value_attr`

- **type**: `array`
- **type**: `array` or `callable`
- **default**: `[]`

If you want to add extra attributes to an HTML column value representation (`<td>`) you can use the attr option.
Expand All @@ -159,3 +159,17 @@ $builder
])
;
```

You can pass a `callable` to perform a dynamic attribute generation:

```php #
$builder
->addColumn('quantity', NumberColumnType::class, [
'value_attr' => function (int $quantity, Product $product) {
return [
'class' => $quantity === 0 && !$product->isDisabled() ? 'text-danger' : '',
],
},
])
;
```
8 changes: 6 additions & 2 deletions src/Column/Type/ColumnType.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ public function buildValueView(ColumnValueView $view, ColumnInterface $column, a
$view->data = $normData;
$view->value = $viewData;

if (is_callable($attr = $options['value_attr'])) {
$attr = $attr($normData, $rowData);
}

$view->vars = array_replace($view->vars, [
'row' => $view->parent,
'data_table' => $view->parent->parent,
Expand All @@ -73,7 +77,7 @@ public function buildValueView(ColumnValueView $view, ColumnInterface $column, a
'value' => $view->value,
'translation_domain' => $options['value_translation_domain'] ?? $view->parent->vars['translation_domain'] ?? null,
'translation_parameters' => $options['value_translation_parameters'] ?? [],
'attr' => $options['value_attr'],
'attr' => $attr,
]);

if (true === $export = $options['export']) {
Expand Down Expand Up @@ -133,7 +137,7 @@ public function configureOptions(OptionsResolver $resolver): void
->setAllowedTypes('property_accessor', [PropertyAccessorInterface::class])
->setAllowedTypes('getter', ['null', 'callable'])
->setAllowedTypes('header_attr', ['array'])
->setAllowedTypes('value_attr', ['array'])
->setAllowedTypes('value_attr', ['array', 'callable'])
->setInfo('label', 'A user-friendly label that describes a column.')
->setInfo('header_translation_domain', 'Translation domain used to translate the column header.')
->setInfo('header_translation_parameters', 'Parameters used within the column header translation.')
Expand Down

0 comments on commit 2dde783

Please sign in to comment.