Skip to content

About

Easily manage persistent checkbox selections and key-value settings in Symfony applications.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

Tests

Persistent State Bundle


This Symfony bundle provides a unified and robust solution for managing persistent user interface state. It handles two key areas:

  1. Selections: Efficient handling of bulk operations (e.g., "Select All" across multiple pages of a paginated list).
  2. Preferences: Storing key-value settings for various contexts (e.g., user, company).

It features a flexible architecture based on context resolvers and support for various storage backends (Session, Redis, Doctrine), allowing you to elegantly solve UI state persistence without boilerplate code in your controllers.

Features

  • Selection Management: Track selected items (IDs) across pagination.
  • Preference Management: Store and retrieve arbitrary user/context settings.
  • Context Resolvers: Automatically resolve context (e.g., current user) for storage.
  • Twig Integration: Easy-to-use Twig functions and filters.
  • Stimulus Integration: Ready-to-use Stimulus controller for interactive selections.
  • Multiple Storages: Support for Session (default), Doctrine, and easily extensible for others (e.g., Redis).
  • CLI Support: Debug preferences directly from the terminal.

Requirements

  • PHP: ^8.1
  • Symfony: ^6.4 | ^7.4 | ^8.0

Installation

Install the bundle via Composer:

composer require tito10047/persistent-state-bundle

If you are using Symfony Flex, the bundle will be registered automatically. Otherwise, add it to your config/bundles.php:

return [
    // ...
    Tito10047\PersistentStateBundle\PersistentStateBundle::class => ['all' => true],
];

For Stimulus integration, ensure you have Symfony UX Stimulus installed and configured.

Usage Scenarios

1. Simple Selection (e.g., Shopping Cart)

use Tito10047\PersistentStateBundle\Selection\Service\SelectionManagerInterface;

class CartController
{
    public function __construct(
        private readonly SelectionManagerInterface $selectionManager,
    ) {}

    public function add(User $user, Product $product)
    {
        $cartSelection = $this->selectionManager->getSelection( 'cart',$user);
        $cartSelection->select($product, [
            'quantity' => 1,
            'added_at' => new \DateTime()
        ]);
    }

    public function clear(User $user)
    {
        $this->selectionManager->getSelection('cart',$user)->destroy();
    }
}

2. User Preferences

use Tito10047\PersistentStateBundle\Preference\Service\PreferenceManagerInterface;

class SettingsController
{
    public function __construct(
        private readonly PreferenceManagerInterface $prefManager,
    ) {}

    public function updateTheme(User $user, string $theme)
    {
        $preferences = $this->prefManager->getPreference($user);
        $preferences->set('theme', $theme);
    }
}

In Twig:

<body class="theme-{{ preference(app.user, 'theme', 'light') }}">
    Company Setting: {{ company|pref('some_setting') }}
</body>

3. Bulk Actions with Stimulus

This bundle provides a Stimulus controller to handle "Select All" and individual row selections.

<div {{ persistent_selection_stimulus_controller("main_logs", null, {
    selectAllClass: 'btn-primary',
    unselectAllClass: 'btn-outline-secondary',
}) }}>
    <div class="mb-2">
        <button class="btn btn-sm" data-action="tito10047--persistent-state-bundle--selection#selectCurrentPage">
            Select Visible
        </button>
        <button class="btn btn-sm" data-action="tito10047--persistent-state-bundle--selection#selectAll">
            Select All
        </button>
    </div>

    <ul class="list-group">
        {% for log in logs %}
            <li class="list-group-item">
                {{ persistent_selection_row_selector("main_logs", log) }}
                {{ log.name }}
            </li>
        {% endfor %}
    </ul>
</div>

Selection count and the change event

Every selection request answers with {"selected": 3, "total": 120} (selected is null when it can't be computed yet). The controller uses it to:

  • fill elements marked as count / total targets,
  • set the selectAll checkbox to checked / indeterminate,
  • dispatch tito10047--persistent-state-bundle--selection:change with event.detail = {selected, total}.
<span data-tito10047--persistent-state-bundle--selection-target="count">{{ persistent_selection_count("main_logs") }}</span>
of
<span data-tito10047--persistent-state-bundle--selection-target="total">{{ persistent_selection_total("main_logs") }}</span>
selected

Attributes passed to persistent_selection_row_selector[_all]() override the defaults, including data-action — e.g. persistent_selection_row_selector_all("main_logs", {'data-action': 'my-dialog#ask'}) lets your own controller ask "all pages or this page?" first and then call selectAll / selectCurrentPage of the selection controller.

Changing the source (filters)

registerSelection() with a different source (for example the same query with another filter) replaces the remembered "all" set, so after Select All only rows of the current source are selected and getTotal() reflects the current source. By default the selection itself is kept; pass onSourceChange to reset it whenever the source differs from the last registered one (the first registration counts as a change, the same source on another page does not):

use Tito10047\PersistentStateBundle\Enum\OnSourceChange;

// filter changed -> nothing selected
$selection = $this->selectionManager->registerSelection('main_logs', $qb, onSourceChange: OnSourceChange::UNSELECT_ALL);
// filter changed -> everything of the new filter selected
$selection = $this->selectionManager->registerSelection('main_logs', $qb, onSourceChange: OnSourceChange::SELECT_ALL);

In your controller to perform the action:

public function deleteSelected(User $user)
{
    $selection = $this->selectionManager->getSelection('main_logs', $user);
    $ids = $selection->getSelectedIdentifiers();
    
    // ... perform deletion
}

Configuration

Default configuration (optional to override in config/packages/persistent_state.yaml):

persistent_state:
    preference:
        managers:
            default:
                storage: '@persistent_state.preference.storage.session'
    selection:
        managers:
            default:
                storage: '@persistent_state.selection.storage.session'

See docs/full_config.md for more advanced configuration, including Doctrine storage setup.

Console Commands

debug:preference

Inspect stored preferences for a specific context.

php bin/console debug:preference "user_15" --manager=default

Testing

Run tests using PHPUnit:

composer test

License

This bundle is released under the MIT License.

About

Easily manage persistent checkbox selections and key-value settings in Symfony applications.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages