Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Filament Calculator Laravel Package

ariefng/filament-calculator

A Filament plugin that adds a simple calculator tool to your admin panel. Useful for quick calculations while managing data, with easy installation and seamless integration into Filament pages and resources.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ariefng/filament-calculator
    

    Publish the package assets (if needed):

    php artisan vendor:publish --provider="Ariefng\FilamentCalculator\FilamentCalculatorServiceProvider" --tag="filament-calculator-assets"
    
  2. Register the Action Add the CalculatorAction to a Filament Table or Form field:

    use Ariefng\FilamentCalculator\Actions\CalculatorAction;
    
    CalculatorAction::make()
        ->label('Open Calculator')
        ->modalHeading('Enter Calculation')
        ->modalWidth('50%')
        ->expression('(value * 2) + 10') // Default expression (optional)
        ->successfulAction(function (string $result) {
            return action('edit')->withResult($result);
        }),
    
  3. Attach to a Field Apply the action to a TextInput field in a Table column or Form field:

    TextInput::make('price')
        ->columnSpanFull()
        ->actions([
            CalculatorAction::make(),
        ]),
    

First Use Case

  • Scenario: A Table displaying product prices where users need to quickly calculate adjusted values (e.g., discounts, taxes).
  • Implementation:
    use Filament\Tables\Table;
    use Ariefng\FilamentCalculator\Actions\CalculatorAction;
    
    Table::make(Product::class, [
        'columns' => [
            TextInput::make('price')
                ->actions([
                    CalculatorAction::make()
                        ->expression('value * 0.9') // Apply 10% discount
                        ->successfulAction(fn ($result) => action('edit')->withResult($result)),
                ]),
        ],
    ]);
    
    • Clicking the calculator icon opens a modal with a pre-filled expression.
    • Users can modify the expression (e.g., (value * 0.8) + 5) and submit to update the field.

Implementation Patterns

Common Workflows

  1. Dynamic Expressions Use variables like value (current field value) or taxRate (passed via extraVariables):

    CalculatorAction::make()
        ->expression('(value + taxRate) * quantity')
        ->extraVariables([
            'taxRate' => 0.08,
            'quantity' => 2,
        ]),
    
  2. Form Integration Attach to a Form field for inline calculations:

    TextInput::make('total')
        ->extraAttributes(['readonly' => true])
        ->actions([
            CalculatorAction::make()
                ->expression('basePrice + shipping')
                ->successfulAction(fn ($result) => $this->form->fill(['total' => $result])),
        ]),
    
  3. Conditional Logic Disable the calculator based on field state:

    TextInput::make('discountedPrice')
        ->visible(fn ($record) => $record->is_discounted)
        ->actions([
            CalculatorAction::make()
                ->visible(fn ($record) => $record->is_discounted),
        ]),
    

Integration Tips

  • Localization: Override the modal labels via language files (resources/lang/).
  • Styling: Customize the modal width/height or add CSS classes:
    CalculatorAction::make()
        ->modalWidth('60%')
        ->modalHeight('400px'),
    
  • Validation: Validate expressions server-side by parsing the submitted result:
    $this->form->fill([
        'calculated_value' => $this->validateExpression($result),
    ]);
    private function validateExpression(string $expression): float {
        // Implement logic to ensure $expression is safe/evaluable.
    }
    

Gotchas and Tips

Pitfalls

  1. Expression Injection Risks

    • Issue: Malicious users could submit harmful expressions (e.g., system('rm -rf /')).
    • Fix: Sanitize or restrict expressions to a whitelist of allowed functions/operators.
      // Example: Only allow basic arithmetic.
      $allowedFunctions = ['+', '-', '*', '/', 'abs'];
      if (!preg_match("/^[0-9+\-*/().\s]+$/", $expression)) {
          throw ValidationException::withMessages(['expression' => 'Invalid characters.']);
      }
      
  2. Modal Overlap

    • Issue: Calculator modal may overlap with other UI elements.
    • Fix: Adjust modalWidth or use z-index in custom CSS:
      CalculatorAction::make()
          ->extraAttributes(['class' => 'filament-calculator--custom']),
      
      .filament-calculator--custom .modal-content {
          z-index: 9999;
      }
      
  3. Field Type Mismatch

    • Issue: Calculator assumes numeric input; errors occur with non-numeric values.
    • Fix: Cast the field to a numeric type or add validation:
      TextInput::make('price')
          ->numeric()
          ->rules(['numeric']),
      

Debugging Tips

  • Check Console Logs: Open browser dev tools (F12) to inspect modal initialization errors.
  • Verify Assets: Ensure the package’s JS/CSS is loaded:
    npm run dev  # If using Vite
    php artisan view:clear
    
  • Test Expressions: Use a simple expression first (e.g., value + 1) to isolate issues.

Extension Points

  1. Custom Modal Content Override the default modal template by publishing and modifying:

    php artisan vendor:publish --tag="filament-calculator-views"
    

    Edit resources/views/vendor/filament-calculator/modal.blade.php.

  2. Add Buttons Extend the modal with additional buttons (e.g., "Save & Close"):

    CalculatorAction::make()
        ->extraModalButtons([
            Button::make('Save')
                ->action('saveAndClose'),
        ]),
    
  3. Hooks for Pre/Post Calculation Use Filament’s beforeFill or afterFill hooks to modify behavior:

    $this->form->fill([
        'calculated_field' => $result,
    ])->afterFill(function () {
        // Trigger additional logic (e.g., update related records).
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky