search

Home  >  Q&A  >  body text

Best way to store checkbox value in session when paginating

I work with Symfony and Twig. I currently have a twig page that contains a list of products, I use a foreach loop to display them, and set up pagination to limit the display of products.

I have a form in this page which has a checkbox as input and when I go to the next page I need to check the save checkbox in the session

I tried to do it by adding this code

There is some code and I've added some comments in the paginated view and controller to explain what I'm trying to do.

My loop view:

<form>
    <div class="row" >
        {%  for annonce in annonces %}

            <div class="col-12 col-md-6 col-lg-4">
                        <p class="text text--blue text--bold m-0 text--medium mt-2">
                            {{ annonce._source.titre }}
                        </p>
                        <p class="m-0">{{ 'Réf' }}: {{ annonce._source.reference }}</p>
                        <div class="d-flex mt-2 text--bold">
                            <div class="d-flex me-2">
                                {{  annonce._source.ville }}
                            </div>
                        </div>
                    <div>
                        <input type="checkbox" name="checkbox[]" id="checkbox_pdf" value="{{annonce._id}}" multiple/>
                    </div>

            </div>

        {% endfor %}
    </div>
    <input type="submit" id="pdf_submit" value="Create PDF" name="submit_pdf" class="btn btn-primary">
</form>

Page view:

// I tried to add a onclick : onclick='document.forms["name"].submit(); return false;' on each pagination link combined with the save of the value in session with my controller but doesn't work

<div class="col d-flex justify-content-between align-items-center">
    <div class="d-flex">
        {% if page > 0 %}
            <a href="#" data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':0, 'type':'frontoffice'}) }}" data-target="pagination-target">
                «
            </a>
            <a href="#"  data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':page-1, 'type':'frontoffice'}) }}"  data-target="pagination-target">
                {{ 'Précédent' }}
            </a>
        {% else %}
            <a href="#" disabled="disabled" >
                {{ 'Précédent' }}
            </a>
        {% endif %}
    </div>
    <div>
        <ul class="list-unstyled pagination m-0">
            {% for i in (page+1)..(page+4) %}
                {% if i <= numberOfMaxPage %}
                    {% if i == (page+1) %}
                        <li>
                            <a href="#" data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':(i-1), 'type':'frontoffice'}) }}" data-target="pagination-target">
                                {{ i }}
                            </a>
                        </li>
                    {% else %}
                        <li>
                            <a href="#"  data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':(i-1), 'type':'frontoffice'}) }}" data-target="pagination-target">
                                {{ i }}
                            </a>
                        </li>
                    {% endif %}
                {% endif %}
            {% endfor %}
        </ul>
    </div>
    <div class="d-flex">
        {% if page < (numberOfMaxPage-1) %}
            <a href="#"  data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':page+1, 'type':'frontoffice'}) }}" data-target="pagination-target">
                {{ 'Suivant' }}
            </a>
            <a href="#"  data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':numberOfMaxPage-1, 'type':'frontoffice'}) }}" data-target="pagination-target">
                »
            </a>
        {% endif %}
    </div>
</div>

Pagination JS:

$( document ).ready(function() {
            $(document).on('click', 'a.pagination',function(e) {
                e.preventDefault();
                $.ajax({
                    url: $(this).data('uri'),
                }).done(function(html) {
                    $('#pagination-target').html(html);
                    $('html,body').animate({scrollTop: $('#pagination-target').offset().top - 80}, 200);
                    var $scrollable = document.getElementById('pagination-target');
                    $scrollable.scrollIntoView();

                });
            });
        });

In my controller I render the view like this:

public function search(Request $request, ?SecteurGeographique $secteurGeographique, AnnonceRepository $annonceRepository): Response
    {
        $selectId = $request->get('checkbox');
        $selected = $annonceRepository->findById($selectId);

// I tried to add this code to save my values
        
if (isset($selectId))
        {
            $session = new Session();
            $session->set('checkbox',$selectId);
        }else{
            echo 'false';
            $session = new Session();
            $session->clear();
        }

return $this->render('front/annonce/list.html.twig', array(
                        'annonces' => $results['hits']['hits'],
                        'total'  => $results['hits']['total']['value'],
                        'website' => $website,
                        'page' => $request->query->getInt('page')
                    ));
}

Is it better to save my php in session or in ajax?

Thank you in advance

P粉592085423P粉592085423275 days ago385

reply all(1)I'll reply

  • P粉189606269

    P粉1896062692024-02-26 15:36:31

    Actually, if I understand your code correctly, you don't actually need to use sessions.

    I assume, when you submit the form, you need to post all the checkbox values ​​immediately to generate the PDF.

    If this is what you are trying to do, you should just store the checkbox list directly via JavaScript and make sure everything is sent when the form is submitted.

    According to this theory, there may be an HTML home page:

    {% for annonce in annonces %}

    {{ annonce._source.titre }}

    {{ 'Réf' }}: {{ annonce._source.reference }}

    {{ annonce._source.ville }}

    {% endfor %}

    Here you can see I added the invisible div #savedCheckboxes. This will allow us to save all checkboxes when you change pages. I also fixed a bit of your HTML, but nothing major.

    Then you should update your pagination javascript:

    $(document).ready(function() {
        $(document).on('click', 'a.pagination',function(e) {
            e.preventDefault();
            // Save all the selected checkboxes by moving them to #savedCheckboxes
            $('.checkboxPDF:checked').appendTo($('#savedCheckboxes'))
    
            // Do your pagination like you did
            $.ajax({
                url: $(this).data('uri'),
            }).done(function(html) {
                $('#pagination-target').html(html);
    
                // If the user come to a previous page, verify if he did selected a checkbox
                $('#pagination-target .checkboxPDF').each(function(i, element) {
                    // If the checkbox already exists in the #savedCheckboxes, then select this checkBox & remove it from #savedCheckboxes
                  var savedCheckbox = $('#savedCheckboxes .checkboxPDF[value="' element.val() '"]')
                  if(savedCheckbox.length > 0) {
                     element.click() // Select this checkbox
                     savedCheckbox.remove() // Remove it from the hidden selection
                  }
                })
    
                $('html,body').animate({scrollTop: $('#pagination-target').offset().top - 80}, 200);
                var $scrollable = document.getElementById('pagination-target');
                $scrollable.scrollIntoView();
            });
        });
     });

    The magic is done... When you submit the form, you will always receive all lists with selected checkboxes, even those that are no longer shown due to pagination.

    reply
    0
  • Cancelreply