Weave 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

Sortable Behavior Bundle Laravel Package

codeclipse/sortable-behavior-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require codeclipse/sortable-behavior-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Codeclipse\SortableBehaviorBundle\CodeclipseSortableBehaviorBundle::class => ['all' => true],
    ];
    
  2. Configure for Doctrine ORM Update config/packages/codeclipse_sortable_behavior.yaml:

    codeclipse_sortable_behavior:
        db_driver: orm  # default, no need to specify
        position_field:
            entities:
                App\Entity\YourEntity: position
    
  3. Extend Your Admin Class Add SortableInterface to your entity and implement getSortableGroups():

    use Codeclipse\SortableBehaviorBundle\Model\SortableInterface;
    
    class YourEntity implements SortableInterface
    {
        // ...
        public function getSortableGroups()
        {
            return ['group1', 'group2'];
        }
    }
    
  4. Enable Sorting in Admin Override configureListFields in your Admin class:

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('name')
            ->add('_sortable', 'sortable', [
                'sortable_group' => 'group1',
            ]);
    }
    
  5. Clear Cache

    php bin/console cache:clear
    

First Use Case

Add sortable functionality to a SonataAdmin listing for a Product entity:

  • Configure position_field for App\Entity\Product (e.g., sort_order).
  • Add _sortable field to the list with a group (e.g., category).
  • Test by dragging items or using up/down buttons in the admin UI.

Implementation Patterns

Workflows

  1. Basic Sorting

    • Use _sortable field in configureListFields with a predefined group.
    • Example:
      $listMapper->add('_sortable', 'sortable', [
          'sortable_group' => 'default_group',
      ]);
      
  2. Dynamic Groups

    • Override getSortableGroups() in your entity to return dynamic groups based on logic (e.g., user roles).
    • Example:
      public function getSortableGroups()
      {
          return $this->isPremium() ? ['premium'] : ['standard'];
      }
      
  3. Custom Templates

    • Replace default up/down buttons with drag-and-drop:
      # config/packages/codeclipse_sortable_behavior.yaml
      codeclipse_sortable_behavior:
          templates:
              move: '@YourBundle/Sortable/_drag_drop.html.twig'
      
    • Create a Twig template extending @CodeclipseSortableBehavior/Default/_sort_drag_drop.html.twig.
  4. MongoDB Integration

    • Configure db_driver: mongodb and ensure your entity uses Doctrine\ODM\MongoDB\Mapping\Annotations.
    • Example position field:
      /**
       * @MongoDB\Field(type="int")
       */
      private $sortRank;
      
  5. Batch Updates

    • Use the sort action in SonataAdmin to reorder multiple items at once:
      $listMapper->add('_sortable', 'sortable', [
          'sortable_group' => 'batch_group',
          'batch_update' => true,
      ]);
      

Integration Tips

  • Event Listeners: Extend sorting logic by subscribing to codeclipse.sortable.pre_save or codeclipse.sortable.post_save events.
    // src/EventListener/SortableListener.php
    public static function getSubscribedEvents()
    {
        return [
            'codeclipse.sortable.pre_save' => 'onPreSort',
        ];
    }
    
  • Validation: Add validation to position_field in your entity (e.g., @Assert\NotBlank).
  • Permissions: Restrict sorting to specific roles using SonataAdmin’s security system:
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper->add('_sortable', 'sortable', [
            'sortable_group' => 'admin_only',
            'access_control' => 'ROLE_ADMIN',
        ]);
    }
    

Gotchas and Tips

Pitfalls

  1. Field Name Mismatch

    • Ensure the position_field in config matches the actual field name in your entity (case-sensitive).
    • Debug: Check php bin/console debug:container codeclipse_sortable_behavior for loaded config.
  2. Cache Issues

    • After changing config or templates, always run:
      php bin/console cache:clear
      php bin/console cache:pool:clear cache.app
      
    • Clear browser cache if drag-and-drop stops working.
  3. Group Misconfiguration

    • If sorting doesn’t appear, verify:
      • The sortable_group in configureListFields matches a group returned by getSortableGroups().
      • Groups are defined in the config under sortable_groups.entities.
  4. Doctrine Events Conflict

    • Avoid naming your position field position if you use other bundles that also define lifecycle callbacks (e.g., prePersist/preUpdate).
  5. MongoDB Quirks

    • Ensure your MongoDB schema includes a unique index on the position field to prevent duplicates:
      /**
       * @MongoDB\Index(keys={"sortRank"="asc"}, options={"unique"=true})
       */
      

Debugging

  • Enable Debug Mode: Set APP_DEBUG=1 in .env to see Symfony profiler data for sortable actions.
  • Log Events: Temporarily add a listener to log sortable events:
    public function onPreSort(SortableEvent $event)
    {
        \Log::debug('Sortable event:', [
            'entity' => $event->getEntity()->getId(),
            'group' => $event->getGroup(),
            'position' => $event->getPosition(),
        ]);
    }
    
  • Check Database: Verify the position field is updated correctly:
    -- ORM Example
    SELECT id, position FROM your_entity ORDER BY position;
    

Extension Points

  1. Custom Sort Logic

    • Override the SortableBehavior service to modify sorting behavior:
      # config/services.yaml
      Codeclipse\SortableBehaviorBundle\Sortable\SortableBehavior:
          arguments:
              $positionField: 'custom_position'
              $groupField: 'custom_group'
      
  2. Add UI Feedback

    • Extend the Twig template to show real-time updates or loading indicators:
      {# @YourBundle/Sortable/_drag_drop.html.twig #}
      {% extends '@CodeclipseSortableBehavior/Default/_sort_drag_drop.html.twig' %}
      {% block sortable_script %}
          {{ parent() }}
          <script>
              $(document).on('sortupdate', function() {
                  alert('Order updated!');
              });
          </script>
      {% endblock %}
      
  3. Bulk Reordering

    • Implement a custom action in SonataAdmin to reorder all items in a group at once:
      protected function configureListActions(ListMapper $listMapper)
      {
          $listMapper->add('reorder_group', 'button', [
              'template' => '@App/Admin/reorder_group.html.twig',
              'route' => ['name' => 'app_admin_reorder', 'parameters' => ['group' => 'your_group']],
          ]);
      }
      
  4. Fallback for Non-Sortable Groups

    • Disable sortable field if no groups are defined:
      $listMapper->add('_sortable', 'sortable', [
          'sortable_group' => 'default',
          'disabled' => $this->getSortableGroups() === [],
      ]);
      
  5. Localization

    • Translate sortable labels/buttons by extending Twig templates and using Symfony’s translation system:
      {% trans from 'SonataAdminBundle' %}Move up{% endtrans %}
      
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.
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings