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

Useful Bundle Laravel Package

acutex/useful-bundle

Symfony bundle providing handy extras for everyday projects: Ajax autocomplete, dependent entity and date-range form types, plus Doctrine DQL functions (IF, IFNULL, ROUND, DATE_DIFF). Can be used with SonataAdmin as filter types.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the bundle to your composer.json (preferred over deps file for modern Laravel/Symfony projects):

    composer require acutex/useful-bundle
    

    Register the bundle in config/bundles.php (Symfony) or manually in AppServiceProvider (Laravel via Symfony bridge):

    return [
        // ...
        Shtumi\UsefulBundle\ShtumiUsefulBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Ajax Autocomplete Use the AjaxAutocompleteType for search-as-you-type fields (e.g., user lookup):

    use Shtumi\UsefulBundle\Form\Type\AjaxAutocompleteType;
    
    $builder->add('user', AjaxAutocompleteType::class, [
        'route' => 'app_user_autocomplete', // Define this route in `routes.yaml`
        'choice_label' => 'fullName',       // Property to display
        'min_length' => 2,                  // Min chars to trigger search
        'placeholder' => 'Search users...',
    ]);
    

    Route Example (config/routes.yaml):

    app_user_autocomplete:
        path: /api/users/autocomplete
        controller: App\Controller\UserController::autocompleteAction
        methods: GET
    
  3. First Use Case: DQL Functions Use custom DQL functions in Doctrine queries (e.g., IF for conditional logic):

    $qb = $entityManager->createQueryBuilder();
    $qb->select('u')
       ->from('App\Entity\User', 'u')
       ->where('IF(u.isActive = 1, 1, 0) = 1'); // Equivalent to CASE WHEN
    

Implementation Patterns

Form Types Workflows

  1. Ajax Autocomplete

    • Frontend Integration: Works with any JS framework (Symfony UX Turbo, Alpine.js, or vanilla JS).
    • Backend Logic: Create a controller method to return JSON:
      public function autocompleteAction(Request $request): JsonResponse
      {
          $query = $request->query->get('query');
          $users = $this->userRepository->findByName($query, 10); // Custom repo method
          return $this->json(array_map(fn($u) => ['id' => $u->id, 'text' => $u->fullName], $users));
      }
      
    - **Pagination**: Use `max_results` option to limit results (e.g., `max_results: 10`).
    
    
  2. Dependent Filtered Entity

    • Chain form fields dynamically (e.g., country → region → city):
      $builder->add('country', EntityType::class, ['class' => Country::class])
              ->add('region', DependentFilteredEntityType::class, [
                  'entity_class' => Region::class,
                  'property' => 'country', // Foreign key
                  'dependent_property' => 'country', // Field to filter by
              ]);
      
    • Dynamic Queries: Override getQueryBuilder in your entity repository to filter by parent fields.
  3. Date Range

    • Simplify date filtering in forms:
      $builder->add('dateRange', DateRangeType::class, [
          'widget' => 'single_text', // or 'split'
          'start_date_format' => 'yyyy-MM-dd',
          'end_date_format' => 'yyyy-MM-dd',
      ]);
      
    • Validation: Automatically validates start <= end.

Integration Tips

  • Symfony UX: Pair with Symfony UX (e.g., symfony/ux-autocomplete) for enhanced frontend behavior.
  • SonataAdmin: Use AjaxAutocompleteType as a filter in SonataAdmin:
    $filterBuilder->add('user', 'sonata_type_ajax_autocomplete', [
        'bundle' => 'AppBundle',
        'model' => 'User',
        'property' => 'username',
        'btn_add' => false,
    ]);
    
  • Doctrine Extensions: Combine with stof/doctrine-extensions-bundle for advanced DQL functions.

Gotchas and Tips

Pitfalls

  1. DQL Functions in Laravel

    • Laravel’s Query Builder doesn’t support custom DQL functions natively. Use raw SQL or Doctrine DBAL:
      $query = DB::select("SELECT IF(is_active = 1, 'Yes', 'No') as status FROM users");
      
    • For Eloquent, use DB::raw():
      $users = User::whereRaw('IF(is_active = 1, 1, 0) = 1')->get();
      
  2. Ajax Autocomplete CORS

    • If using API routes, ensure CORS headers are set (Symfony’s NelmioCorsBundle helps):
      # config/packages/nelmio_cors.yaml
      nelmio_cors:
          defaults:
              allow_origin: ["*"]
              allow_methods: ["GET", "POST"]
              allow_headers: ["Content-Type"]
              expose_headers: ["Content-Type"]
      
  3. Dependent Filtered Entity Performance

    • Avoid N+1 queries by eager-loading dependencies:
      // In your repository
      public function findByCountry(QueryBuilder $qb, $countryId)
      {
          return $qb->andWhere('r.country = :country')
                    ->setParameter('country', $countryId)
                    ->leftJoin('r.country', 'c')
                    ->addSelect('c');
      }
      

Debugging

  • Autocomplete Not Loading:
    • Check the route is correctly defined and accessible (test with curl or Postman).
    • Verify the choice_label property exists in your entity.
  • DQL Function Errors:
    • Ensure the function is registered in Doctrine’s dql/function mapping (check config/packages/doctrine.yaml):
      doctrine:
          dql:
              string_functions:
                  IF: Shtumi\UsefulBundle\DQL\IFFunction
                  IFNULL: Shtumi\UsefulBundle\DQL\IFNULLFunction
      

Extension Points

  1. Custom DQL Functions

    • Extend the bundle by adding your own functions in config/packages/shtumi_useful.yaml:
      shtumi_useful:
          dql_functions:
              CONCAT_WS: App\DQL\ConcatWsFunction
      
    • Implement Doctrine\ORM\Query\AST\Functions\FunctionNode for new functions.
  2. Form Type Overrides

    • Override form types in your bundle’s Resources/config/services.yaml:
      services:
          App\Form\Type\CustomAutocompleteType:
              parent: Shtumi\UsefulBundle\Form\Type\AjaxAutocompleteType
              tags: [form.type]
      
  3. Date Range Localization

    • Customize date formats per locale by overriding the type’s configureOptions:
      $builder->add('dateRange', DateRangeType::class, [
          'date_range_options' => [
              'start_date_format' => 'd/m/Y', // Override for FR locale
          ],
      ]);
      

Config Quirks

  • Bundle Prefix: The bundle uses Shtumi\UsefulBundle, but Laravel’s autoloader may need adjustment if using acutex/useful-bundle directly. Ensure composer dump-autoload is run post-install.
  • Symfony 5+: Some features may require Symfony 5.1+ (e.g., typed properties). Check the bundle’s composer.json for constraints.
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