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 Country Code Field Laravel Package

tapp/filament-country-code-field

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require tapp/filament-country-code-field:"^2.0"
    

    Ensure your project uses Filament 4.x/5.x (check composer.json for filament/filament version).

  2. Publish Config (optional, for customization):

    php artisan vendor:publish --tag="filament-country-code-field-config"
    
  3. First Use Case: Add the field to a Filament Resource (e.g., UserResource):

    use Tapp\FilamentCountryCodeField\Forms\Components\CountryCodeSelect;
    
    public static function form(Form $form): Form
    {
        return $form->schema([
            CountryCodeSelect::make('country_code'), // Default 2-letter ISO code
        ]);
    }
    
  4. Verify:

    • The field appears as a flag-based dropdown in the form.
    • Test saving/loading a record to confirm persistence.

Implementation Patterns

Core Workflows

1. Form Integration

  • Basic Usage:
    CountryCodeSelect::make('country_code')
        ->label('Country')
        ->required()
        ->columnSpanFull(); // Optional: Full-width on mobile
    
  • Customization:
    ->searchable() // Enable search
    ->placeholder('Select a country')
    ->options(Country::all()->pluck('name', 'code')) // Override default options
    

2. Table Column

  • Display country codes as flags + names:
    use Tapp\FilamentCountryCodeField\Tables\Columns\CountryCodeColumn;
    
    public static function table(Table $table): Table
    {
        return $table->columns([
            CountryCodeColumn::make('country_code')
                ->label('Country')
                ->sortable(),
        ]);
    }
    

3. Table Filter

  • Add a filterable dropdown to tables:
    use Tapp\FilamentCountryCodeField\Tables\Filters\CountryCodeSelectFilter;
    
    public static function table(Table $table): Table
    {
        return $table->filters([
            CountryCodeSelectFilter::make('country_code')
                ->label('Filter by Country')
                ->placeholder('All countries'),
        ]);
    }
    

4. Validation

  • Leverage Filament’s built-in validation:
    CountryCodeSelect::make('country_code')
        ->rules(['required', 'size:2']) // ISO 2-letter code
    

5. Localization

  • Supports multi-language (e.g., Portuguese via pt_BR):
    // In config/filament-country-code-field.php
    'locale' => app()->getLocale(), // Auto-detect or set manually
    

Advanced Patterns

Dynamic Data Binding

  • Bind to a model attribute or relationship:
    CountryCodeSelect::make('address.country_code')
        ->relationship('address', 'country_code')
    

Custom Styling

  • Override CSS via published config:
    // config/filament-country-code-field.php
    'styles' => [
        'flagSize' => '24px', // Adjust flag icon size
        'dropdownWidth' => '300px',
    ],
    
  • Or extend the package’s assets (see Gotchas).

API/Backend Integration

  • Ensure your database column matches the expected format (e.g., country_code VARCHAR(2)).
  • For API responses, cast the attribute:
    // In User model
    protected $casts = [
        'country_code' => 'string',
    ];
    

Testing

  • Test form submission:
    $this->get('/admin/resources/users/create')
        ->assertSee('Country'); // Verify field renders
    $this->post('/admin/resources/users', [
        'country_code' => 'US',
    ])->assertRedirect(); // Test save
    

Gotchas and Tips

Pitfalls

  1. Version Mismatch:

    • Error: Class 'CountryCodeSelect' not found.
    • Fix: Ensure filament/filament and tapp/filament-country-code-field versions align (check compatibility table).
  2. Empty State Handling:

    • Issue: Flags may not render if country_code is null in the database.
    • Fix: Use ->nullable() or provide a default:
      CountryCodeSelect::make('country_code')
          ->default('US')
      
  3. CSS Registration:

    • Error: Styles not loading (fixed in v2.1.1).
    • Fix: Run npm run dev or npm run build if customizing assets.
  4. Performance:

    • Warning: Loading all countries may slow down forms/tables with many records.
    • Optimization: Use ->options() to limit choices or lazy-load via API.
  5. Locale Fallback:

    • Issue: Country names display in English even with app()->setLocale('fr').
    • Fix: Publish config and set 'locale' => 'fr' in config/filament-country-code-field.php.

Debugging Tips

  1. Check Rendered HTML:

    // In a Filament widget or blade view
    {{ dd($this->getTable()->getColumns()) }}
    

    Verify the CountryCodeColumn is registered correctly.

  2. Log Country Data:

    // In a Resource's form builder
    CountryCodeSelect::make('country_code')
        ->afterStateUpdated(fn ($state) => \Log::info('Selected:', $state));
    
  3. Database Schema:

    • Ensure your migration uses:
      $table->string('country_code', 2)->nullable();
      

Extension Points

  1. Custom Country Options:

    • Override the default list (e.g., for internal codes):
      CountryCodeSelect::make('country_code')
          ->options([
              'INTL' => 'International',
              'US' => 'United States',
          ]);
      
  2. Add Flags Dynamically:

    • Extend the package’s CountryCodeSelect class to fetch flags from an API:
      // app/Filament/Extensions/CustomCountryCodeSelect.php
      use Tapp\FilamentCountryCodeField\Forms\Components\CountryCodeSelect as BaseSelect;
      
      class CustomCountryCodeSelect extends BaseSelect {
          public static function getOptions(): array {
              return Cache::remember('custom_country_options', now()->addHours(1), function () {
                  return Http::get('https://api.example.com/countries')->json();
              });
          }
      }
      
  3. Filament 5+ Features:

    • Use ->columnSpanFull() for responsive design:
      CountryCodeSelect::make('country_code')
          ->columnSpanFull()
          ->extraAttributes(['class' => 'w-full']);
      
  4. Testing Helpers:

    • Mock country data in tests:
      $this->actingAs($user)
          ->get('/admin/resources/users/create')
          ->assertSee('🇺🇸 United States'); // Verify flag + name
      

Pro Tips

  • Combine with Other Fields:
    CountryCodeSelect::make('country_code')
        ->afterStateUpdated(fn ($state) => $this->dispatchBrowserEvent('update-itinerary'))
    
  • Use in Widgets:
    public static function getWidgetData(): array {
        return [
            'country' => CountryCodeColumn::make('country_code')
                ->state(fn () => 'US'),
        ];
    }
    
  • Local Development:
    • Test with php artisan filament:install if migrating from Filament 3.x.
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope