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

Shtumi Useful Bundle Laravel Package

avalia/shtumi-useful-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require avalia/shtumi-useful-bundle
    

    (Note: The original README uses a legacy deps file method; Composer is preferred for modern Laravel/Symfony projects.)

  2. Register the Bundle (in config/bundles.php for Symfony/Laravel):

    return [
        // ...
        Shtumi\UsefulBundle\ShtumiUsefulBundle::class => ['all' => true],
    ];
    
  3. Enable Twig Form Theming (in config/packages/twig.yaml):

    twig:
        form_themes: ['@ShtumiUsefulBundle/fields.html.twig']
    
  4. Load jQuery (in a base layout template):

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    

First Use Case: Ajax Autocomplete

// In a Symfony FormBuilder
$builder->add('user', Shtumi\UsefulBundle\Form\Type\AjaxAutocompleteType::class, [
    'label' => 'Search Users',
    'route' => 'user_autocomplete', // Custom route for autocomplete data
    'min_length' => 2,
]);

Route Definition (in config/routes.yaml):

user_autocomplete:
    path: /api/user/autocomplete
    controller: App\Controller\UserController::autocompleteAction

Implementation Patterns

1. Form Types

Ajax Autocomplete

  • Workflow:

    1. Define a controller method to return JSON data (e.g., UserRepository::findByName()).
    2. Use AjaxAutocompleteType in forms with route pointing to the controller.
    3. Customize appearance via Twig (e.g., {% extends '@ShtumiUsefulBundle/AjaxAutocomplete/autocomplete.html.twig' %}).
  • Integration with SonataAdmin:

    // In a SonataAdmin service
    $formMapper
        ->add('user', 'shtumi_ajax_autocomplete', [
            'route' => 'sonata_admin_user_autocomplete',
            'route_parameters' => ['admin' => 'sonata.admin.user'],
        ]);
    

Dependent Filtered Entity

  • Use Case: Cascading dropdowns (e.g., Country → Region → City).
  • Implementation:
    $builder->add('country', EntityType::class, ['class' => Country::class]);
    $builder->add('region', Shtumi\UsefulBundle\Form\Type\DependentFilteredEntityType::class, [
        'entity' => Region::class,
        'property' => 'name',
        'dependent_property' => 'country',
        'dependent_entity' => Country::class,
    ]);
    

Date Range

  • Workflow:
    $builder->add('date_range', Shtumi\UsefulBundle\Form\Type\DateRangeType::class, [
        'widget' => 'single_text', // or 'split'
        'start_date_options' => ['label' => 'Start Date'],
        'end_date_options' => ['label' => 'End Date'],
    ]);
    
    • Validation: Use DateRange constraint:
      use Shtumi\UsefulBundle\Validator\Constraints\DateRange;
      /**
       * @Assert\DateRange(
       *     startDate = "start_date",
       *     endDate = "end_date",
       *     message = "Invalid date range"
       * )
       */
      

2. DQL Functions

  • Usage in Repositories:
    $qb = $this->createQueryBuilder('u');
    $qb->select('IF(u.is_active = 1, "Yes", "No") as status');
    $qb->orWhere('DATE_DIFF(u.created_at, CURRENT_DATE) > 30');
    
  • Custom Functions: Extend via Shtumi\UsefulBundle\Doctrine\DQL\Function\AbstractFunction.

3. SonataAdmin Integration

  • Example: Add autocomplete to a SonataAdmin list filter:
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->add('name')
            ->add('user', 'shtumi_ajax_autocomplete', [
                'route' => 'sonata_admin_user_autocomplete',
                'route_parameters' => ['admin' => 'sonata.admin.user'],
            ]);
    }
    

Gotchas and Tips

Pitfalls

  1. jQuery Dependency:

    • The bundle requires jQuery 1.9.1+. Conflicts may arise with modern jQuery versions (e.g., 3.x). Test thoroughly.
    • Fix: Use a CDN with a specific version or bundle a local copy.
  2. Route Configuration:

    • Autocomplete routes must return JSON with data and label fields. Example:
      return new JsonResponse($users->map(fn($u) => ['id' => $u->id, 'label' => $u->name]));
      
    • Gotcha: Forgetting to return JSON will break the autocomplete UI.
  3. Doctrine DQL Functions:

    • Functions like DATE_DIFF require Doctrine DBAL support. For MySQL, ensure your platform is configured (e.g., Doctrine\DBAL\Platforms\MySQLPlatform).
    • Tip: Use IFNULL for NULL-safe operations:
      $qb->select('IFNULL(u.email, "N/A") as email');
      
  4. Twig Theming:

    • Override templates in templates/ShtumiUsefulBundle/ to customize appearance. Clear cache after changes:
      php bin/console cache:clear
      

Debugging Tips

  1. Autocomplete Not Loading:

    • Check browser console for 404 errors on the autocomplete route.
    • Verify the route returns valid JSON (e.g., {"data": [...]}).
  2. Dependent Filtered Entity Not Updating:

    • Ensure the dependent_property matches the entity’s property name exactly (case-sensitive).
    • Add ajax_options to debug:
      'ajax_options' => ['debug' => true] // Logs AJAX calls to console
      
  3. Date Range Validation Failing:

    • Confirm the DateRange constraint is applied to the form type, not the entity property.
    • Use start_date/end_date as field names in the constraint.

Extension Points

  1. Custom Autocomplete Data:

    • Extend Shtumi\UsefulBundle\Form\Type\AjaxAutocompleteType to modify data processing:
      class CustomAutocompleteType extends AjaxAutocompleteType {
          public function configureOptions(OptionsResolver $resolver) {
              $resolver->setDefaults([
                  'custom_data' => null, // Add your custom option
              ]);
          }
      }
      
  2. Add New DQL Functions:

    • Create a custom function class (e.g., MyCustomFunction) extending AbstractFunction and register it in the bundle’s Resources/config/doctrine.xml:
      <doctrine-dql>
          <function name="MY_CUSTOM_FUNC" class="App\Doctrine\DQL\MyCustomFunction"/>
      </doctrine-dql>
      
  3. SonataAdmin List Filters:

    • Create a custom filter type by extending Shtumi\UsefulBundle\Form\Type\AjaxAutocompleteType and register it in SonataAdmin’s filter configuration.

Laravel-Specific Notes

While this bundle is Symfony-focused, Laravel developers can adapt it via:

  1. Symfony Bridge: Use symfony/flex or symfony/console to integrate Symfony components.
  2. Form Handling: Replace Symfony’s FormBuilder with Laravel’s Form facade (e.g., Form::macro() for custom types).
  3. DQL Functions: Use Laravel’s query builder or raw SQL for DQL functions, or integrate Doctrine via doctrine/dbal.
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