Heim  >  Fragen und Antworten  >  Hauptteil

Die beste Möglichkeit, den Kontrollkästchenwert beim Paginieren in der Sitzung zu speichern

Ich arbeite mit Symfony und Twig. Ich habe derzeit eine Twig-Seite, die eine Liste von Produkten enthält. Ich verwende eine foreach-Schleife, um sie anzuzeigen, und richte die Paginierung ein, um die Anzeige von Produkten einzuschränken.

Ich habe auf dieser Seite ein Formular, das ein Kontrollkästchen als Eingabe enthält, und wenn ich zur nächsten Seite gehe, muss ich das Kontrollkästchen zum Speichern in der Sitzung aktivieren

Ich habe es versucht, indem ich diesen Code hinzugefügt habe

Es gibt Code und ich habe der paginierten Ansicht und dem Controller einige Kommentare hinzugefügt, um zu erklären, was ich zu tun versuche.

Meine Loop-Ansicht:

<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>

Seitenaufruf:

// 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>

JS für Paginierung:

$( 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 meinem Controller rendere ich die Ansicht wie folgt:

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')
                    ));
}

Ist es besser, mein PHP in der Sitzung oder in Ajax zu speichern?

Vielen Dank im Voraus

P粉592085423P粉592085423211 Tage vor309

Antworte allen(1)Ich werde antworten

  • P粉189606269

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

    实际上,如果我正确理解您的代码,您实际上并不需要使用会话。

    我假设,当您提交表单时,您需要立即发布所有复选框值以生成 PDF。

    如果这是尝试,您应该只直接通过 JavaScript 存储复选框列表,并确保在提交表单时发送所有内容。

    按照这个理论,可能会有 HTML 主页:

    {% for annonce in annonces %}

    {{ annonce._source.titre }}

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

    {{ annonce._source.ville }}

    {% endfor %}

    在这里,您可以看到我添加了不可见的 div #savedCheckboxes。这将使我们能够在您更改页面时保存所有复选框。我还修正了一点你的 HTML,但没什么大不了的。

    那么你应该更新你的分页 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();
            });
        });
     });

    魔法就完成了...当您提交表单时,您将始终收到所选复选框的所有列表,甚至是那些由于分页而不再显示的列表。

    Antwort
    0
  • StornierenAntwort