From d1a01b3694d5bc26ff7c54790ad8136ebcf83a1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20CROMBEZ?= <777666+jcrombez@users.noreply.github.com> Date: Tue, 24 Oct 2023 07:37:10 +0000 Subject: [PATCH] add a way to autodetect column types --- src/Grid/Column.php | 19 ++++++++++++++++--- src/Resources/views/_column_value.html.twig | 6 ++++-- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/Grid/Column.php b/src/Grid/Column.php index af9db1a..2084e3a 100644 --- a/src/Grid/Column.php +++ b/src/Grid/Column.php @@ -9,7 +9,7 @@ class Column { public string $name; public $value; - public string $template; + private ?string $template; public array $templateParameters; public ?string $sortable; public $sortableQuery; @@ -19,17 +19,30 @@ public function __construct( string|callable $value = null, string $template = null, array $templateParameters = [], - string|array $sortable = null, + string|array $sortable = null, callable|string|null $sortableQuery = null ) { $this->name = $name; $this->value = $value ?? fn($item) => $item; - $this->template = $template ?? Template::TEXT; + $this->template = $template; $this->templateParameters = $templateParameters; $this->sortable = $sortable; $this->sortableQuery = $sortableQuery; } + public function getTemplate(?object $entity = null): string + { + if ($this->template !== null) { + return $this->template; + } + + if ($entity !== null && is_array($this->getValue($entity))) { + return Template::ARRAY; + } + + return Template::TEXT; + } + public function getValue(object $entity) { if (is_callable($this->value)) { diff --git a/src/Resources/views/_column_value.html.twig b/src/Resources/views/_column_value.html.twig index 47c12d9..6aa60f0 100644 --- a/src/Resources/views/_column_value.html.twig +++ b/src/Resources/views/_column_value.html.twig @@ -1,6 +1,8 @@ -{% include [grid.theme ~ '/column_type/' ~ column.template, '@KibaticDatagrid/column_type/' ~ column.template, column.template] with { +{% set template = column.template(item) %} + +{% include [grid.theme ~ '/column_type/' ~ template, '@KibaticDatagrid/column_type/' ~ template, template] with { 'column': column, 'parameters': column.templateParameters, 'item': item, 'value': column.value(item) -} %} \ No newline at end of file +} %}