首頁  >  問答  >  主體

分頁時在會話中儲存複選框值的最佳方法

我與 Symfony 和 Twig 合作。我目前有一個包含產品清單的樹枝頁面,我使用 foreach 循環顯示它們,並設定分頁來限制產品的顯示。

我在此頁面中有一個表單,其中有一個複選框作為輸入,當我轉到下一頁時,我需要在會話中選中保存複選框

我嘗試透過添加此程式碼來做到這一點

有一些程式碼,我在分頁視圖和控制器中添加了一些註解來解釋我的嘗試。

我的循環視圖:

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

分頁檢視:

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

$( 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();

                });
            });
        });

在我的控制器中,我像這樣渲染視圖:

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

在會話中保存我的 php 還是在 ajax 中更好?

提前謝謝您

P粉592085423P粉592085423211 天前300

全部回覆(1)我來回復

  • 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();
            });
        });
     });

    魔法就完成了...當您提交表單時,您將始終收到所選複選框的所有列表,甚至是那些由於分頁而不再顯示的列表。

    回覆
    0
  • 取消回覆