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

Sulu Form City Select Bundle Laravel Package

eekes/sulu-form-city-select-bundle

Adds a City Select field to Sulu forms, letting frontend users pick a city from a predefined list. Install via Composer and enable the bundle; the new field appears automatically in the form field list.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Installation:

    composer require eekes/sulu-form-city-select-bundle
    

    Register the bundle in config/bundles.php:

    Eekes\Sulu\FormCitySelectBundle\EekesSuluFormCitySelectBundle::class => ['all' => true],
    
  2. First Use Case:

    • Access the City Select field in Sulu’s form builder under available form fields.
    • Configure the field in your Sulu form definition (e.g., config/forms.yml or via the admin UI).
    • Test the field in a frontend form to ensure cities are selectable and submitted correctly.
  3. Where to Look First:

    • Sulu Form Documentation: Review how to add custom fields to Sulu forms.
    • Bundle Configuration: Check for any required config (e.g., API keys for city data) in config/packages/eekes_sulu_form_city_select.yaml.
    • Frontend Integration: Verify the field renders correctly in your Sulu frontend templates (e.g., Resources/views/forms/_city_select.html.twig).

Implementation Patterns

1. Basic Field Integration

  • Add to a Sulu Form:
    # config/forms.yml
    my_form:
        fields:
            city:
                type: city_select
                label: "Select a City"
                options:
                    required: true
                    placeholder: "Choose a city..."
    
  • Access Submitted Data:
    public function store(Request $request)
    {
        $city = $request->input('city'); // e.g., "Berlin" or "New York"
        // Process city data (e.g., save to database or use in logic)
    }
    

2. Dynamic City Data

  • Customize City Source: If the bundle fetches cities from an external API, configure it in config/packages/eekes_sulu_form_city_select.yaml:
    eekes_sulu_form_city_select:
        api:
            enabled: true
            endpoint: "https://api.example.com/cities"
            cache_ttl: 3600 # Cache cities for 1 hour
    
  • Override City List: Use a service to inject custom city data:
    // src/Service/CityProvider.php
    class CityProvider implements CityProviderInterface
    {
        public function getCities(): array
        {
            return [
                ['id' => 1, 'name' => 'Paris'],
                ['id' => 2, 'name' 'London'],
            ];
        }
    }
    
    Bind the service in services.yaml:
    services:
        App\Service\CityProvider: ~
    eekes_sulu_form_city_select.city_provider: '@App\Service\CityProvider'
    

3. Frontend Customization

  • Extend Twig Templates: Override the default template for the city select field:

    php artisan vendor:publish --tag=sulu-form-city-select-templates
    

    Customize templates/forms/fields/city_select.html.twig to add classes, icons, or validation messages.

  • Add JavaScript Behavior: Use Sulu’s form event system to attach custom logic:

    // assets/js/app.js
    Sulu.Form.on('citySelect:change', function(event) {
        const city = event.detail.value;
        console.log('Selected city:', city);
        // Trigger additional actions (e.g., load city-specific data)
    });
    

4. Backend Processing

  • Validate City Input:
    $request->validate([
        'city' => 'required|string|exists:cities,name', // Assuming a `cities` table
    ]);
    
  • Use City Data: Fetch city details (e.g., coordinates, region) from a database or API:
    $cityData = City::where('name', $request->city)->first();
    $coordinates = $cityData->coordinates; // e.g., ["lat" => 52.5200, "lng" => 13.4050]
    

5. Localization

  • Translate City Names: Use Sulu’s translation system to localize city labels:
    # translations/messages.en.yml
    city_select:
        paris: "Paris (France)"
        london: "London (UK)"
    
    Reference translations in your form:
    fields:
        city:
            options:
                choices:
                    paris: "%city_select.paris%"
                    london: "%city_select.london%"
    

Gotchas and Tips

Pitfalls

  1. Missing API Configuration:

    • If the bundle relies on an external API (e.g., for city data), ensure the endpoint is configured and accessible. Test with curl or Postman before integrating:
      curl https://api.example.com/cities
      
    • Fix: Set api.enabled: false in config if using a custom provider, or debug API errors in Sulu logs (var/log/dev.log).
  2. Caching Issues:

    • City data cached via the bundle may not update immediately. Clear the cache after changes:
      php artisan cache:clear
      php artisan sulu:cache:clear
      
    • Tip: Use cache_ttl: 0 in config for development to bypass caching.
  3. Field Not Appearing in Form Builder:

    • Ensure the bundle is enabled in bundles.php and dependencies (e.g., SuluFormBundle) are installed.
    • Debug: Check if the field appears in php artisan sulu:form:fields:list. If not, verify the bundle’s service tags are registered.
  4. Case Sensitivity in City Names:

    • City names submitted via the form may not match database entries due to case differences (e.g., "berlin" vs. "Berlin").
    • Fix: Normalize input in validation:
      $request->validate([
          'city' => 'required|string|exists:cities,name',
      ]);
      $normalizedCity = mb_strtolower($request->city);
      
  5. Performance with Large City Lists:

    • Rendering a dropdown with thousands of cities can slow down the frontend.
    • Tip: Implement server-side filtering or lazy-loading:
      // Use a library like Select2 with AJAX
      $('.city-select').select2({
          ajax: {
              url: '/api/cities',
              dataType: 'json',
              delay: 250,
              data: function(params) {
                  return { q: params.term };
              }
          }
      });
      

Debugging

  1. Log City Data: Add logging to inspect city data flow:

    use Psr\Log\LoggerInterface;
    
    class CitySelectHandler
    {
        public function __construct(private LoggerInterface $logger) {}
    
        public function handleCitySelection(string $city): void
        {
            $this->logger->info('City selected', ['city' => $city]);
            // Process city...
        }
    }
    
  2. Check Bundle Events: The bundle may dispatch events (e.g., city.select). Listen for them in your code:

    use Symfony\Component\EventDispatcher\EventDispatcherInterface;
    
    $dispatcher->addListener('city.select', function($event) {
        $city = $event->getCity();
        // Handle event...
    });
    
  3. Database Mismatches: If cities submitted via the form don’t match database entries, verify:

    • The name column in your cities table matches the submitted values.
    • No typos in city names (e.g., "New York" vs. "New York City").

Extension Points

  1. Custom City Data Source: Implement Eekes\Sulu\FormCitySelectBundle\Provider\CityProviderInterface to replace the default provider:

    class DatabaseCityProvider implements CityProviderInterface
    {
        public function getCities(): array
        {
            return City::query()->pluck('name')->toArray();
        }
    }
    

    Bind the service in services.yaml:

    eekes_sulu_form_city_select.city_provider: '@App\Service\DatabaseCityProvider'
    
  2. Add City Metadata: Extend the city select field to include additional data (e.g., country, population):

    fields:
        city:
            type: city_select
            options:
                display_properties: ['name', 'country', 'population']
    

    Update the template to render extra properties:

    {# templates/forms/fields/city_select.html.twig #}
    <div class="city-info">
        {{ field.value.name }} ({{ field.value.country }})
    </div>
    
  3. Geocoding Integration: Automatically fetch coordinates for selected cities using a service like Google Maps or OpenStreetMap:

    use Geocoder\Geocoder;
    use Geocoder\Provider\OpenStreetMap\OpenStreetMap;
    
    $geocoder
    
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony