Skip to content

Instantly share code, notes, and snippets.

@saqueib
Last active June 14, 2024 01:38
Show Gist options
  • Save saqueib/6228deeef4c188462bb4a8a137b82a85 to your computer and use it in GitHub Desktop.
Save saqueib/6228deeef4c188462bb4a8a137b82a85 to your computer and use it in GitHub Desktop.
Add Widget Support on Statamic Runway index pages
<?php
'resources' => [
\App\Models\Order::class => [
'name' => 'Orders',
// define all widgets for order resource
'widgets' => [
[
'type' => 'earning',
'width' => 50
],
[
'type' => 'collection',
'collection' => 'pages',
'width' => 50
],
],
],
],
],
@extends('statamic::layout')
@section('title', $title)
@section('wrapper_class', 'max-w-full')
@section('content')
<div class="widgets @container flex flex-wrap -mx-4 py-2">
@foreach($widgets as $widget)
<div
class="widget w-full md:{{ Statamic\Support\Str::tailwindWidthClass($widget['width']) }} {{ $widget['classes'] }} mb-8 px-4">
{!! $widget['html'] !!}
</div>
@endforeach
</div>
<div class="flex items-center justify-between mb-6">
<h1 class="flex-1">{{ $title }}</h1>
@if(! $resource->readOnly())
@can('create', $resource)
<a
class="btn-primary"
href="{{ cp_route('runway.create', ['resourceHandle' => $resource->handle()]) }}"
>
{{ __('Create :resource', [
'resource' => $resource->singular()
]) }}
</a>
@endcan
@endif
</div>
<runway-listing
:filters="{{ $filters->toJson() }}"
:listing-config='@json($listingConfig)'
:initial-columns='@json($columns)'
action-url="{{ $actionUrl }}"
initial-primary-column="{{ $primaryColumn }}"
></runway-listing>
@endsection
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View as ViewFacade;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\View;
use Statamic\Widgets\Loader;
class RunwayViewServiceProvider extends ServiceProvider
{
/**
* Bootstrap services.
*/
public function boot(): void
{
// add the widgets to the resources index view
ViewFacade::composer('runway::index', function (View $view) {
$resource = $view->resource;
$loader = app(Loader::class);
$view->with('widgets', $this->getDisplayableWidgets($resource, $loader));
});
}
private function getDisplayableWidgets($resource, $loader)
{
$widgets = $resource->config()->get('widgets', []);
return collect($widgets)
->map(function ($config) {
return is_string($config) ? ['type' => $config] : $config;
})
->map(function ($config) use ($loader) {
return [
'widget' => $widget = $loader->load(array_get($config, 'type'), $config),
'classes' => $widget->config('classes'),
'width' => $widget->config('width', 100),
'html' => (string)$widget->html(),
];
})
->reject(function ($widget) {
return empty($widget['html']);
});
}
}
@saqueib
Copy link
Author

saqueib commented Jun 14, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment