Tom
Tom

Reputation: 1223

Store filters in session in LexikFormFilterBundle

Currently I store filters in session like this:

// Filter action
if ('filter' == $request->get('filter_action')) {
    // Bind values from the request
    $filterForm->handleRequest($request);

    if ($filterForm->isValid()) {
        // Build the query from the given form object
        $filterUpdater->addFilterConditions($filterForm, $queryBuilder);
        // Save filter to session
        $filterData = $filterForm->getData();
        $session->set(sprintf('%sControllerFilter', $this->filterName), $filterData);
        $session->set(sprintf('%sControllerFilterPage', $this->filterName), 1);
    }
} else {
    // Get filter from session
    if ($session->has(sprintf('%sControllerFilter', $this->filterName))) {
        $filterData = $session->get(sprintf('%sControllerFilter', $this->filterName));
        foreach ($filterData as $key => $filter) {
            if (\is_object($filter)) {
                $filterData[$key] = $em->merge($filter);
            }
        }
        $filterForm = $this->createFilterForm($filterData, $this->getSiteFromSession($request));
        $filterUpdater->addFilterConditions($filterForm, $queryBuilder);
    }
}

But due to EntityManager::merge() deprecations I need to change this solution. Any ideas how to do it? The solution is to skip using EntityFilterType and use ChoiceFilterType but I don't want to, cause EntityFilterType is a much more comfortable solution.

If I remove lines that are responsible for merging entities from session, then I get error:

Entity of type "App\Entity\Category" passed to the choice field must be managed. Maybe you forget to persist it in the entity manager?

Upvotes: 0

Views: 180

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76601

merge is used to re-attach a detached entity. persist tells Doctrine that the entity is to be saved, so it achieves the re-attach. This way you achieve that the entity will be managed, as the error message suggests.

You can read more here: https://symfony.com/doc/current/doctrine.html#persisting-objects-to-the-database

Upvotes: 1

Related Questions