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

Date Collection Type Laravel Package

drugento/date-collection-type

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run:

    composer require --prefer-dist drugento/date-collection-type
    

    Ensure Akeneo PIM Community Edition v1.7.x is installed.

  2. Register the Bundle Add to app/AppKernel.php:

    new \Pim\Bundle\DateCollectionTypeBundle\PimDateCollectionTypeBundle(),
    
  3. First Use Case Create a DateCollection attribute type in Akeneo:

    • Navigate to Settings > Attributes > Create Attribute.
    • Select DateCollection as the attribute type.
    • Define a label (e.g., validity_periods) and save.
  4. Verify UI The attribute will now appear in product forms with a date range picker (as shown in the README screenshot).


Implementation Patterns

Workflows

  1. Attribute Definition Use the DateCollection type for:

    • Product lifecycle tracking (e.g., launch dates, promotions).
    • Seasonal availability (e.g., winter/summer ranges).
    • Compliance deadlines (e.g., certification periods).

    Example YAML (if extending via custom bundle):

    pim_enrich:
        attribute:
            validity_periods:
                type: pim_date_collection
                label: "Validity Periods"
                order: 100
    
  2. Data Population

    • Manual Entry: Use the Akeneo UI to add date ranges via the picker.
    • API/Import: Pass data as an array of objects with start/end dates:
      {
        "validity_periods": [
          {"start": "2023-10-01", "end": "2023-12-31"},
          {"start": "2024-01-15", "end": null} // Open-ended range
        ]
      }
      
  3. Querying Data Retrieve values in PHP:

    $product = $productRepository->find($id);
    $dateRanges = $product->getValidityPeriods(); // Returns array of DateRange objects
    foreach ($dateRanges as $range) {
        echo $range->getStart()->format('Y-m-d') . " to " . $range->getEnd()->format('Y-m-d');
    }
    
  4. Validation

    • Ensure startend (handled automatically by the UI/picker).
    • Custom validation via Akeneo’s validation system:
      use Pim\Bundle\DateCollectionTypeBundle\Validator\Constraints as DateCollectionAssert;
      
      /**
       * @DateCollectionAssert\DateCollection(
       *     maxRanges=5,
       *     message="Maximum 5 date ranges allowed."
       * )
       */
      

Integration Tips

  • Custom Templates: Override the Twig template for the date picker by copying: vendor/drugento/date-collection-type/src/Resources/views/PimDateCollectionType/attribute.html.twig to app/Resources/PimDateCollectionType/views/.

  • Export/Import: Use the pim_enrich:export and pim_enrich:import commands with the validity_periods field mapped to your CSV/JSON.

  • API Platform: If using API Platform, ensure the DateRange object is serialized correctly:

    # config/packages/api_platform.yaml
    api_platform:
        formats:
            jsonld:
                mime_types: ['application/ld+json']
                jsonld_context:
                    '@context': '/contexts/Product'
                    validity_periods:
                        '@type': 'array'
                        '@context': 'https://schema.org/Date'
    

Gotchas and Tips

Pitfalls

  1. Akeneo Version Lock

    • Issue: Bundle requires Akeneo 1.7.x. Upgrading to newer versions may break compatibility.
    • Fix: Check the GitHub issues for patches or fork the bundle.
  2. Date Format Mismatch

    • Issue: Importing dates in non-ISO format (e.g., MM/DD/YYYY) may fail silently.
    • Fix: Validate dates before import or use a pre-import script to normalize formats.
  3. Empty Ranges

    • Issue: Saving a range with both start and end as null may cause errors.
    • Fix: Add validation to reject empty ranges:
      $validator = $this->get('validator');
      $errors = $validator->validate($dateRanges, [
          new \Pim\Bundle\DateCollectionTypeBundle\Validator\Constraints\DateCollection([
              'allowEmptyRanges' => false,
          ]),
      ]);
      
  4. UI Glitches

    • Issue: Date picker may not render in Akeneo’s admin panel after installation.
    • Fix:
      • Clear cache: php bin/console cache:clear.
      • Check browser console for JS errors (e.g., missing jQuery or Akeneo’s admin assets).

Debugging

  • Log Data: Dump attribute values during imports/exports:
    use Symfony\Component\Debug\Debug;
    Debug::dump($product->getValidityPeriods());
    
  • Database Inspection: Verify data in pim_catalog_value table:
    SELECT * FROM pim_catalog_value
    WHERE attribute_id = (SELECT id FROM pim_catalog_attribute WHERE code = 'validity_periods');
    

Extension Points

  1. Custom Date Range Logic Extend the DateRange class to add methods:

    namespace App\Entity;
    
    use Pim\Bundle\DateCollectionTypeBundle\Entity\DateRange as BaseDateRange;
    
    class CustomDateRange extends BaseDateRange {
        public function isOverlappingWith(BaseDateRange $other): bool {
            return $this->getStart() <= $other->getEnd() && $this->getEnd() >= $other->getStart();
        }
    }
    

    Register as a service:

    services:
        app.date_range.type:
            class: App\Entity\CustomDateRange
            tags:
                - { name: pim_date_collection.range_type }
    
  2. Custom Validation Create a custom constraint:

    namespace App\Validator;
    
    use Symfony\Component\Validator\Constraint;
    
    class NoFutureDates extends Constraint {
        public $message = 'Date ranges cannot be in the future.';
    }
    

    Then validate in your controller:

    $validator = $this->get('validator');
    $errors = $validator->validate($dateRanges, [
        new NoFutureDates(),
    ]);
    
  3. Localization Override translation keys (e.g., for the "Add Date Range" button):

    # app/Resources/translations/messages.en.yml
    pim_date_collection:
        add_date_range: "Add Custom Period"
    

Performance Tips

  • Batch Processing: For large imports, process DateCollection attributes in chunks to avoid memory issues.
  • Indexing: If querying date ranges frequently, add a database index:
    CREATE INDEX idx_pim_catalog_value_validity_periods ON pim_catalog_value (attribute_id, locale, value);
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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
spatie/mailcoach-vapor