I'm currently facing a challenge to display a color picker value in one of my CRUDs in backpack for laravel. One of my CRUDs is having a color attribute and I'm using a color_picker field when creating a new entry.
I don't want to display just the string value of the selected color, I want to display a rectangle containing the selected color, something like this (Farbe = color):
I've tried the following things already:
CRUD::addColumn([
'name' => 'color',
'label' => 'Farbe',
'type' => 'custom_html',
'value' => '<svg width="20" height="20">
<rect width="20" height="20" style="fill:'. $this->crud->getCurrentEntry()->color . ';" />
</svg>',
'escaped' => false, //optional, if the "value" should be escaped when displayed in the page.
]);
But it didn't work, most likely because the getCurrentEntry method is not available in the setupListOperation.
Then I tried it with a model_function:
CRUD::addColumn([
// run a function on the CRUD model and show its return value
'name' => 'color',
'label' => 'Farbe', // Table column heading
'type' => 'model_function',
'function_name' => 'getColorRectangle',
//'attribute' => 'route' // the method in your Model
// 'function_parameters' => [$one, $two], // pass one/more parameters to that method
// 'limit' => 100, // Limit the number of characters shown
]);
with this function in the model:
public function getColorRectangle()
{
return "<svg width='400' height='110'>
<rect width='300' height='100' style='fill:" . $this->color . ";stroke-width:3;stroke:rgb(0,0,0)'></rect>
</svg>";
}
But again, unfortunately without success.
Happy for any suggestions, maybe I'm already blind after struggling for several hours on this topic.
Cheers
Personally, I would rather create a custom column type for that. That has quite a few benefits:
And it's super-easy to do. See [the docs here](create a custom column type) but in your particular case it would be something like this:
Step 1. Create a resources/views/vendor/backpack/crud/columns/color.blade.php
file.
Step 2. In that file, copy-paste your HTML code but use $entry->{$column['name']}
to get the value of that column:
<svg width="20" height="20">
<rect width="20" height="20" style="fill:'. $entry->{$column['name']} . ';" />
</svg>
Step 3. Use this new column inside your CrudController
CRUD::addColumn([
'name' => 'color',
'label' => 'Farbe',
'type' => 'color',
]);