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

Timestamptype Bundle Laravel Package

bukashk0zzz/timestamptype-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bukashk0zzz/timestamptype-bundle
    

    Register the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3/5):

    return [
        // ...
        Bukashk0zzz\TimestampTypeBundle\Bukashk0zzzTimestampTypeBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Use the timestamp field type in a form builder:

    use Bukashk0zzz\TimestampTypeBundle\Form\Type\TimestampType;
    
    $builder->add('eventTime', TimestampType::class, [
        'label' => 'Event Timestamp',
        'widget' => 'single_text', // or 'text' (default)
        'attr' => ['class' => 'form-control'],
    ]);
    
  3. Where to Look First:

    • Bundle Docs (limited but sufficient).
    • src/Form/Type/TimestampType.php for customization options.
    • Symfony’s Form Component for general usage patterns.

Implementation Patterns

Core Workflows

  1. Basic Timestamp Input:

    // Single-text input (HH:MM:SS)
    $builder->add('deadline', TimestampType::class, ['widget' => 'single_text']);
    
    // Text input (HH:MM:SS or HH:MM)
    $builder->add('duration', TimestampType::class, ['widget' => 'text']);
    
  2. Validation and Constraints: Combine with Symfony’s validators:

    $builder->add('timeout', TimestampType::class, [
        'constraints' => [
            new Assert\NotBlank(),
            new Assert\Type(['type' => 'string', 'message' => 'Invalid timestamp format']),
        ],
    ]);
    
  3. Customizing Rendering: Override the template (e.g., templates/bukashk0zzz_timestamp/timestamp_widget_single_text.html.twig):

    <input type="text" {{ block('widget_attributes') }} placeholder="HH:MM:SS">
    
  4. Data Transformation: The bundle automatically converts between:

    • String ("12:34:56") ↔ DateTime/DateTimeImmutable (with 00:00:00 date).
    • Use data_transformer for custom logic:
      $builder->add('customTime', TimestampType::class, [
          'data_transformer' => new CustomTimestampTransformer(),
      ]);
      
  5. Integration with Laravel (via Symfony Bridge): If using Laravel with Symfony components (e.g., laravel/symfony-bridge):

    • Register the bundle in config/app.php under extra.bundles.
    • Use the type in Laravel Forms (e.g., collective/html) by extending the form builder.

Advanced Patterns

  1. Dynamic Widget Selection:

    $builder->add('timeField', TimestampType::class, [
        'widget' => $isMobile ? 'single_text' : 'text',
    ]);
    
  2. Localization: Override translation keys (e.g., form.timestamp.hour, form.timestamp.minute) in your translation files.

  3. API/JSON Serialization: Use with Symfony Serializer or API Platform:

    # config/serializer/Entity.Event.yaml
    App\Entity\Event:
        attributes:
            eventTime: '=serializer.timestamp_format'
    
  4. Testing: Mock the type in PHPUnit:

    $formFactory = $this->get('form.factory');
    $form = $formFactory->create(TimestampType::class);
    $form->submit('12:34:56');
    $this->assertEquals('12:34:56', $form->getData());
    

Gotchas and Tips

Pitfalls

  1. Date Handling:

    • The bundle ignores the date part (always uses 00:00:00). If you need full datetime, use Symfony’s datetime type instead.
    • Edge Case: Submitting "25:00:00" will fail validation (use Assert\Regex if allowing custom formats).
  2. Symfony Version Compatibility:

    • Tested with Symfony 3.4–5.4. May require adjustments for newer versions (e.g., FormBuilder API changes).
    • Fix: Check composer.json for symfony/form constraints and update accordingly.
  3. Template Overrides:

    • If overriding templates, ensure the base path matches the bundle’s namespace:
      templates/bukashk0zzz_timestamp/timestamp_widget_{widget_name}.html.twig
      
    • Debug Tip: Clear cache (php bin/console cache:clear) after template changes.
  4. Validation Quirks:

    • The default validation expects HH:MM:SS or HH:MM. Customize with:
      $builder->add('time', TimestampType::class, [
          'constraints' => [new Assert\Regex('/^[0-9]{1,2}:[0-9]{2}$/')],
      ]);
      
  5. Performance:

    • The bundle adds minimal overhead. For high-traffic forms, ensure the widget option is optimized (e.g., single_text for mobile).

Debugging Tips

  1. Form Errors: Dump the form errors to identify issues:

    $form->submit($data);
    if (!$form->isValid()) {
        dump($form->getErrors(true)); // Recursive errors
    }
    
  2. Data Flow: Log the transformed data:

    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
        $data = $event->getData();
        error_log('Raw timestamp data: ' . print_r($data, true));
    });
    
  3. Bundle Configuration: Check if the bundle is loaded:

    php bin/console debug:container | grep timestamp
    

    If missing, verify bundles.php or AppKernel.php.


Extension Points

  1. Custom Widgets: Extend TimestampType to add new widget types:

    class CustomTimestampType extends TimestampType {
        public function getBlockPrefix() { return 'custom_timestamp'; }
        public function getParent() { return TimestampType::class; }
        public function configureOptions(OptionsResolver $resolver) {
            $resolver->setDefaults(['widget' => 'custom_widget']);
        }
    }
    
  2. Event Listeners: Hook into form events for preprocessing:

    $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
        $data = $event->getData();
        $event->setData(['HH' => $data['hours'], 'MM' => $data['minutes']]);
    });
    
  3. Database Storage: Use with Doctrine to store timestamps as strings (e.g., string(8) for HH:MM:SS):

    /**
     * @ORM\Column(type="string", length=8)
     */
    private $timeout;
    
  4. Laravel-Specific:

    • For Laravel, create a custom form component:
      use Bukashk0zzz\TimestampTypeBundle\Form\Type\TimestampType;
      use Illuminate\Support\Facades\Form;
      
      Form::macro('timestamp', function ($name, $options = []) {
          return Form::custom($name, TimestampType::class, $options);
      });
      
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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