Column type: nested text #1115
nerbiz
started this conversation in
Show and Tell
Replies: 1 comment 1 reply
-
|
Hello @nerbiz Thanks a lot for sharing this. Cheers. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
For an admin page with menu items (reorderable and nested) I needed more insight in the hierarchy of the items.
This column type shows the hierarchy with arrows, based on a
parent_idcolumn, so it works well with the Reorder Operation.FYI: the arrow icon is from Line Awesome, which is already included by Backpack, so this code has no dependencies of its own.
Screenshot:
Put this code in
resources/views/vendor/backpack/crud/columns/text_nested.blade.php:@php namespace BackpackColumns; use Illuminate\Database\Eloquent\Model; if (! class_exists(TextNested::class)) { class TextNested { /** * @var array Reduces query amount by reusing models */ protected static $modelCache = []; /** * Get a model from the cache, or query it * @param string $fqn Fully qualified class name * @param int $id Model ID * @return Model|null */ public static function getModel(string $fqn, int $id): Model|null { if (! isset(static::$modelCache[$fqn])) { static::$modelCache[$fqn] = []; } if (! isset(static::$modelCache[$fqn][$id])) { static::$modelCache[$fqn][$id] = $fqn::find($id); } return static::$modelCache[$fqn][$id]; } } } // The column name where parent IDs are stored $column['parentIdColumn'] ??= 'parent_id'; // Get all parent models, top-most first $parentModels = collect([]); $currentModel = $entry; $modelClass = get_class($entry); while ($currentModel->{$column['parentIdColumn']} !== null) { $parentModel = TextNested::getModel($modelClass, $currentModel->{$column['parentIdColumn']}); if ($parentModel === null) { break; } $parentModels->prepend($parentModel); $currentModel = $parentModel; } @endphp {{-- Show each parent, followed by a newline with arrow --}} @foreach($parentModels as $index => $parentModel) <span class="d-inline-block mb-2 text-muted"> {{ $parentModel->{$column['name']} }} </span> <br> <i class="las la-level-up-alt text-muted" style="transform: rotate(90deg); margin-left: {{ ($index + 1) * 30 }}px"></i> @endforeach {{-- Show the item itself, after all possible parents --}} {{ $entry->{$column['name']} }}Usage:
Beta Was this translation helpful? Give feedback.
All reactions