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

Timezone Bundle Laravel Package

bertrandom/timezone-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ollietb/bert-timezone-bundle
    

    (Note: The original README uses Git submodules; prefer Composer for modern Laravel/Symfony integration.)

  2. Register the Bundle: Add to config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 2/3):

    Bert\TimezoneBundle\BertTimezoneBundle::class => ['all' => true],
    
  3. First Use Case: Replace Symfony’s default timezone field type in a form:

    {{ form_widget(form.timezone, {'type': 'bert_timezone'}) }}
    

    (Renders a Windows-style dropdown with grouped timezones by region/city.)


Implementation Patterns

Workflow Integration

  1. Form Types: Extend Bert\TimezoneBundle\Form\Type\TimezoneType for customization:

    use Bert\TimezoneBundle\Form\Type\TimezoneType as BaseTimezoneType;
    
    class CustomTimezoneType extends BaseTimezoneType {
        public function configureOptions(OptionsResolver $resolver) {
            $resolver->setDefaults([
                'label' => 'User Timezone',
                'attr'  => ['class' => 'timezone-selector'],
            ]);
        }
    }
    
  2. Validation: Use Symfony’s Timezone validator (works with this bundle):

    # config/validation.yaml
    Bert\TimezoneBundle\Validator\Constraints\Timezone:
        message: "Please select a valid timezone."
    
  3. Dynamic Data: Fetch selected timezone in controllers:

    $timezone = $form->get('timezone')->getData(); // e.g., "America/New_York"
    $dateTime = new \DateTime('now', new \DateTimeZone($timezone));
    
  4. API Responses: Normalize timezone strings for consistency:

    $normalized = \DateTimeZone::createFromPrestring($rawInput)->getName();
    

Laravel-Specific Adaptations

  1. Service Provider: Register the bundle in AppServiceProvider (Symfony 4+):

    public function register() {
        $this->app->register(Bert\TimezoneBundle\BertTimezoneBundle::class);
    }
    
  2. Blade Integration: Use the field type in Laravel forms:

    {!! Form::select('timezone', null, ['type' => 'bert_timezone']) !!}
    
  3. Model Casting: Cast timezone strings in Eloquent models:

    protected $casts = [
        'timezone' => 'string', // Store as "Region/City" format
    ];
    

Gotchas and Tips

Pitfalls

  1. Symfony 2/3 vs. 4+:

    • The bundle targets Symfony 2. Original deps file setup won’t work in Laravel/Symfony 4+. Use Composer.
    • Fix: Replace registerNamespaces with autoload in composer.json:
      "autoload": {
          "psr-4": {
              "Bert\\TimezoneBundle\\": "vendor/ollietb/bert-timezone-bundle/src"
          }
      }
      
  2. Timezone Data Staleness:

    • The bundle ships with static timezone data. For updates, extend the TimezoneDataProvider:
      use Bert\TimezoneBundle\DataProvider\TimezoneDataProviderInterface;
      
      class CustomTimezoneDataProvider implements TimezoneDataProviderInterface {
          public function getTimezones() {
              return \DateTimeZone::listIdentifiers(); // Fetch fresh data
          }
      }
      
    • Register the service in config/services.yaml:
      Bert\TimezoneBundle\DataProvider\TimezoneDataProvider: '@custom_timezone_data_provider'
      
  3. JavaScript Dependencies:

    • The dropdown relies on basic HTML/CSS. For dynamic behavior (e.g., search), add:
      // Example: Initialize Select2 on the timezone field
      $('.timezone-selector').select2();
      
  4. Locale Support:

    • Timezone labels are hardcoded. Override translations in config/packages/bert_timezone.yaml:
      bert_timezone:
          labels:
              "America/New_York": "New York (EDT)"
      

Debugging Tips

  1. Verify Data Flow: Dump the rendered HTML to confirm timezone groups:

    dd($view->renderFragment(form_row(form.timezone)));
    
  2. Check for Conflicts: If the dropdown doesn’t render, ensure:

    • The bundle is enabled in bundles.php.
    • No other bundle overrides the timezone field type.
  3. Fallback to Default: Use Symfony’s native type as a fallback:

    {% if app.environment == 'prod' %}
        {{ form_widget(form.timezone, {'type': 'bert_timezone'}) }}
    {% else %}
        {{ form_widget(form.timezone) }} {# Default Symfony type #}
    {% endif %}
    

Extension Points

  1. Custom Grouping: Override TimezoneGroupProvider to reorder/group timezones:

    class CustomGroupProvider extends TimezoneGroupProvider {
        protected function getGroups() {
            return [
                'Custom/Group' => ['Europe/London', 'Asia/Tokyo'],
            ];
        }
    }
    
  2. API Endpoints: Create a controller to fetch timezones dynamically:

    use Bert\TimezoneBundle\DataProvider\TimezoneDataProviderInterface;
    
    class TimezoneController {
        public function __construct(private TimezoneDataProviderInterface $provider) {}
    
        public function getTimezones() {
            return response()->json($this->provider->getTimezones());
        }
    }
    
  3. Testing: Mock the timezone provider in PHPUnit:

    $this->mock(TimezoneDataProviderInterface::class)
         ->shouldReceive('getTimezones')
         ->andReturn(['UTC' => 'UTC']);
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware