PHP code example of ubertech-za / filament-tree-enhanced

1. Go to this page and download the library: Download ubertech-za/filament-tree-enhanced library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ubertech-za / filament-tree-enhanced example snippets




return [
    /**
     * Tree model fields
     */
    'column_name' => [
        'order' => 'order',
        'parent' => 'parent_id',
        'title' => 'title',
    ],
    /**
     * Tree model default parent key
     */
    'default_parent_id' => -1,
    /**
     * Tree model default children key name
     */
    'default_children_key_name' => 'children',
];




namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use UbertechZa\FilamentTreeEnhanced\Concern\ModelTree;

class ProductCategory extends Model
{
    use ModelTree;

    protected $fillable = ["parent_id", "title", "order"];

    protected $casts = [
        'parent_id' => 'int'
    ];

    protected $table = 'product_categories';
}



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use UbertechZa\FilamentTreeEnhanced\Concern\ModelTree;

class ProductCategory extends Model
{
    use ModelTree;

    protected $fillable = ["parent_id", "title", "order"];

    protected $table = 'product_categories';

    // Default if you need to override

    // public function determineOrderColumnName(): string
    // {
    //     return "order";
    // }

    // public function determineParentColumnName(): string
    // {
    //     return "parent_id";
    // }

    // public function determineTitleColumnName(): string
    // {
    //     return 'title';
    // }

    // public static function defaultParentKey()
    // {
    //     return -1;
    // }

    // public static function defaultChildrenKeyName(): string
    // {
    //     return "children";
    // }

}


php artisan make:filament-tree-widget ProductCategoryWidget



namespace App\Filament\Widgets;

use App\Models\ProductCategory as ModelsProductCategory;
use App\Filament\Widgets;
use Filament\Forms\Components\TextInput;
use UbertechZa\FilamentTreeEnhanced\Widgets\Tree as BaseWidget;

class ProductCategoryWidget extends BaseWidget
{
    protected static string $model = ModelsProductCategory::class;

    // you can customize the maximum depth of your tree
    protected static int $maxDepth = 2;

    protected ?string $treeTitle = 'ProductCategory';

    protected bool $enableTreeTitle = true;

    protected function getFormSchema(): array
    {
        return [
            TextInput::make('title'),
        ];
    }
}



namespace App\Filament\Resources\ProductCategoryResource\Pages;

use App\Filament\Resources\ProductCategoryResource;
use App\Filament\Widgets\ProductCategory;
use Filament\Pages\Actions;
use Filament\Resources\Pages\ListRecords;

class ListProductCategories extends ListRecords
{
    protected static string $resource = ProductCategoryResource::class;

    protected function getActions(): array
    {
        return [
            Actions\CreateAction::make(),
        ];
    }

    protected function getHeaderWidgets(): array
    {
        return [
            ProductCategory::class
        ];
    }
}

public static function getPages(): array
{
    return [
        // ...
        'tree-list' => Pages\ProductCategoryTree::route('/tree-list'),
    ];
}

    use Filament\Actions\CreateAction;

    protected function getActions(): array
    {
        return [
            CreateAction::make(),
            // SAMPLE CODE, CAN DELETE
            //\Filament\Pages\Actions\Action::make('sampleAction'),
        ];
    }

use UbertechZa\FilamentTreeEnhanced\Actions\DeleteAction;
use UbertechZa\FilamentTreeEnhanced\Actions\EditAction;
use UbertechZa\FilamentTreeEnhanced\Actions\ViewAction;

protected function getTreeActions(): array
{
    return [
        ViewAction::make(),
        EditAction::make(),
        DeleteAction::make(),
    ];
}


protected function hasDeleteAction(): bool
{
    return false;
}

protected function hasEditAction(): bool
{
    return true;
}

protected function hasViewAction(): bool
{
    return false;
}

public function getTreeRecordIcon(?\Illuminate\Database\Eloquent\Model $record = null): ?string
{
    if ($record->parent_id != -1) {
        return null; // no icon for child records
    }

    return match ($record->title) {
        'Top' => 'heroicon-o-arrow-up',
        'Bottom' => 'heroicon-o-arrow-down',
        'Shoes' => 'heroicon-o-shopping-bag',
        'Accessories' => 'heroicon-o-briefcase',
        default => null, // no icon for other records
    };
}

public function getNodeCollapsedState(?\Illuminate\Database\Eloquent\Model $record = null): bool
{
    // All tree nodes will be collapsed by default.
    return true;
}

public function getTreeRecordTitle(?\Illuminate\Database\Eloquent\Model $record = null): string
{
    if (! $record) {
        return '';
    }
    $id = $record->getKey();
    $title = $record->{(method_exists($record, 'determineTitleColumnName') ? $record->determineTitleColumnName() : 'title')};
    return "[{$id}] {$title}";
}

protected function configureDeleteAction(DeleteAction $action): DeleteAction
{
    $action
        ->label('Remove Item')
        ->icon('heroicon-o-trash')
        ->color('danger')
        ->te it');

    return $action;
}

protected function configureEditAction(EditAction $action): EditAction
{
    $action
        ->label('Edit Item')
        ->icon('heroicon-o-pencil')
        ->color('primary')
        ->modalHeading('Edit Category')
        ->modalSubmitActionLabel('Save Changes')
        ->slideOver();

    return $action;
}

protected function configureViewAction(ViewAction $action): ViewAction
{
    $action
        ->label('View Details')
        ->icon('heroicon-o-eye')
        ->color('secondary')
        ->modalHeading('Category Details')
        ->modalWidth('2xl')
        ->slideOver();

    return $action;
}



namespace App\Filament\Widgets;

use App\Models\ProductCategory;
use Filament\Forms\Components\TextInput;
use UbertechZa\FilamentTreeEnhanced\Actions\DeleteAction;
use UbertechZa\FilamentTreeEnhanced\Actions\EditAction;
use UbertechZa\FilamentTreeEnhanced\Actions\ViewAction;
use UbertechZa\FilamentTreeEnhanced\Widgets\Tree as BaseWidget;

class ProductCategoryWidget extends BaseWidget
{
    protected static string $model = ProductCategory::class;

    protected function getFormSchema(): array
    {
        return [
            TextInput::make('title')->EditAction(EditAction $action): EditAction
    {
        $action
            ->slideOver()
            ->modalWidth('md');

        return $action;
    }

    protected function configureViewAction(ViewAction $action): ViewAction
    {
        $action
            ->slideOver()
            ->disabled(fn ($record) => $record->parent_id === -1); // Disable for root items

        return $action;
    }
}

php artisan make:filament-tree-page ProductCategory --model=ProductCategory

use Filament\Actions\LocaleSwitcher;
use UbertechZa\FilamentTreeEnhanced\Concern\ModelTree;
use Spatie\Translatable\HasTranslations;

class Category extends Model
{
    use HasTranslations;
    use TreeModel;

    protected $translatable = [
        'title',
    ];
}

use App\Models\Category as TreePageModel;
use UbertechZa\FilamentTreeEnhanced\Concern\TreeRecords\Translatable;
use UbertechZa\FilamentTreeEnhanced\Pages\TreePage as BasePage;

class Category extends BasePage
{
    use Translatable;

    protected static string $model = TreePageModel::class;

    public function getTranslatableLocales(): array
    {
        return ['en', 'fr'];
    }

    protected function getActions(): array
    {
        return [
            LocaleSwitcher::make(),
        ];
    }
}

// Generated LocationResource.php
class LocationResource extends TreeResource
{
    protected static ?string $model = Location::class;
    protected static ?string $navigationIcon = 'heroicon-o-map';
    
    public static function getRelations(): array
    {
        return [
            ContactsRelationManager::class,
            // Add more relation managers
        ];
    }
}

// Generated LocationsTree.php  
class LocationsTree extends BaseTree
{
    public static function tree(Tree $tree): Tree
    {
        return $tree->maxDepth(4);
    }
    
    public static function getResource(): string
    {
        return LocationResource::class;
    }
    
    // Action configuration (all enabled by default)
    // protected bool $hasCreateAction = true;
    // protected bool $hasAddChildAction = true; 
    // protected bool $hasEditAction = true;
    // protected bool $hasViewAction = true;
    // protected bool $hasDeleteAction = true;
}

// Enable in config/filament-tree.php
'enable_policy_authorization' => true,

class LocationPolicy
{
    public function viewAny(User $user): bool
    public function create(User $user): bool  
    public function update(User $user, Location $location): bool
    public function delete(User $user, Location $location): bool
}

use UbertechZa\FilamentTreeEnhanced\Actions\CreateChildAction;

protected function getTreeActions(): array
{
    return [
        CreateChildAction::make()
            ->beforeAction(function ($record, $data) {
                // Customize data before creation
                $data['type'] = match($record->type) {
                    'country' => 'state',
                    'state' => 'city',
                    default => 'district'
                };
                return $data;
            })
            ->afterAction(function ($record, $data, $result) {
                // Log, notify, or perform side effects
                activity()->performedOn($result)->log("Created child under {$record->name}");
                return $result;
            }),
    ];
}

use UbertechZa\FilamentTreeEnhanced\Actions\EditAction;
use UbertechZa\FilamentTreeEnhanced\Actions\DeleteAction;

protected function getTreeActions(): array
{
    return [
        EditAction::make()
            ->beforeAction(function ($record, $data) {
                // Validate, prepare, or log before action
                return $data;
            })
            ->afterAction(function ($record, $data, $result) {
                // Clear cache, send notifications, log changes
                return $result;
            }),
            
        DeleteAction::make()
            ->beforeAction(function ($record) {
                // Safety checks
                if ($record->children()->count() > 0) {
                    throw new \Exception('Cannot delete record with children');
                }
                return true;
            }),
    ];
}

return [
    // Existing options...
    
    /**
     * Enable Laravel policy authorization
     */
    'enable_policy_authorization' => false,
    
    /**
     * Policy abilities mapping
     */
    'policy_abilities' => [
        'create' => 'create',
        'createChild' => 'create',
        'edit' => 'update',
        'view' => 'view',
        'delete' => 'delete',
    ],
    
    /**
     * TreeResource configuration
     */
    'resources' => [
        'enabled' => true,
        'namespace' => 'App\\Filament\\Resources',
        'path' => app_path('Filament/Resources'),
    ],
];
bash
php artisan filament:assets
bash
php artisan vendor:publish --tag="filament-tree-enhanced-config"

php artisan make:filament-resource ProductCategory

php artisan make:filament-tree-page ProductCategoryTree --resource=ProductCategory
bash
php artisan vendor:publish --tag="filament-tree-enhanced-views"
bash
php artisan vendor:publish --tag="filament-tree-enhanced-translations"

app/Filament/Resources/Locations/
├── LocationResource.php           # Main resource class
├── Pages/
│   ├── ListLocations.php         # Tree view page (replaces table)
│   ├── CreateLocation.php        # Create page with parent_id support
│   ├── EditLocation.php          # Edit page
│   └── ViewLocation.php          # View page  
├── Schemas/
│   └── LocationForm.php          # Reusable form schema
└── Trees/
    └── LocationsTree.php         # Tree configuration and actions