Динамическое ограничение на страницу Нумерация страниц Knp


Мне нужно простое решение для динамического задания количества записей на странице с помощью пакета разбиения на страницы Knp.

Я прочитал эту страницу записи на странице позволяют пользователю выбирать - разбиение на страницы codeigniter о динамически устанавливаемых ограничениях на страницу, и я знаю, что мне нужен раскрывающийся список с гиперссылкой внутри каждого элемента, который отправляет запрос на сервер, и сервер использует параметр в этом запросе, чтобы установить ограничение на страницу в пакете разбиения на страницы knp. Но я точно не знаю, как справиться с этими действиями на сервере, а также и более сложно для меня, как создавать элементы в выпадающем списке, связанные с общим числом в моем запросе.

Мой контроллер:

public function indexAction()
{   
    $page_title = Util::getFormattedPageTitle("Customers");

    $em    = $this->get('doctrine.orm.entity_manager');
    $dql   = "SELECT a FROM CustomersBundle:Customer a WHERE a.enable = 1 ORDER BY a.id";
    //$query = $em->createQuery($dql);
    //$customers = $query->execute();

    $query = $em->createQuery($dql); 
    $paginator  = $this->get('knp_paginator');
    $pagination = $paginator->paginate(
        $query,
        $this->get('request')->query->get('page', 1)/*page number*/,
        3/*limit per page*/
    );


    // parameters to template
    return $this->render('CustomersBundle:Default:index.html.twig', array(
        'page_title' => $page_title,
        'pagination' => $pagination,
        'image_path' => CustomersConstants::$customers_image_thumb_path
    ));
}

И мой код представления:

    {% extends '::base.html.twig' %}

{% block title %}
    {{ page_title }}
{% endblock %}

{% block body %}
    <h1>
        {{ "customers" }}
    </h1>
    <br />
    {% for customer in pagination %}
    <a href="{{ customer.url }}" target="_blank">
        <div dir="rtl" class="st_simple_box" id="customer{{customer.id}}" >
            <table cellpadding="0" cellspacing="0" width="100%">
                <tr>
                    <td style="vertical-align: top; width: 115px;">
                        {% if customer.imageName is not empty %}
                            <img class="newsimage" src="{{asset(image_path) ~ customer.imageName}}" alt="No Image/>
                        {% else %}
                            <img class="newsimage" src="{{asset('images/vakil_default_small.png') ~ customer.imageName}}" alt="No Image"/>
                        {% endif %}
                    </td>
                    <td style="text-align: center;">
                        <p><span style="font-family: Tahoma;">{{customer.titleFa}}</span></p>
                    </td>
                    <td style="text-align: justify;">
                        <p><span style="font-family: Tahoma;">{{customer.descriptionFa}}</span></p>
                    </td>
                </tr>
            </table>
        </div>
    </a>
    {% endfor %}
    <div class="navigation">
        <span>
        {{ knp_pagination_render(pagination) }}
        </span>
        <!--Here is my drop down html code-->
    </div>
    <br />

{% endblock %}

**

Отредактировано 12 марта 2014 года

   ||||
   ||||
   ||||
  \\\///
   \\//
    \/

Есть ли какой-либо способ настроить MaxItemPerPage в файле cookie на наличие интегрированной переменной и использовать эту переменную или изменять ее, пока в файле twig отображается разбивка на страницы Knp.

Ответ был правильным, но из-за того, что я использовал разбивку на страницы во многих пакеты для разбиения на страницы между моими сущностями, поэтому мне нужна переменная интеграции, чтобы изменить их все. Я использую ваш ответ и настраиваю sliding.html.twig на странице Knp, чтобы получить этот код для "customized_sliding.html.twig"

<div class="ui small pagination menu">
    <div style="clear: both;">
        {% if pageCount > 1 %}
            <div class="pagination" style="float: right;">
                {% if first is defined and current != first %}
                    <a href="{{ path(route, query|merge({(pageParameterName): first})) }}" class="small icon item">
                        <i class="small double angle right icon"></i>
                    </a>
                {% endif %}

                {% if previous is defined %}
                    <a href="{{ path(route, query|merge({(pageParameterName): previous})) }}" class="small icon item">
                        <i class="small angle right icon"></i>
                    </a>
                {% endif %}

                {% for page in pagesInRange %}
                    {% if page != current %}
                        <a href="{{ path(route, query|merge({(pageParameterName): page})) }}" class="small item">
                            {{ page }}
                        </a>
                    {% else %}
                        <a class="small active item">
                            {{ page }}
                        </a>
                    {% endif %}
                {% endfor %}

                {% if next is defined %}
                    <a href="{{ path(route, query|merge({(pageParameterName): next})) }}" class="small icon item">
                        <i class="small angle left icon"></i>
                    </a>
                {% endif %}

                {% if last is defined and current != last %}
                    <a href="{{ path(route, query|merge({(pageParameterName): last})) }}" class="small icon item">
                        <i class="small double angle left icon"></i>
                    </a>
                {% endif %}
            </div>
        {% endif %}
        <div style="float: left;">
            <select name="maxItemPerPage" id="maxItemPerPage">
                <option selected="true" style="display:none;">Number Per Page</option>
                <option id="10">5</option>
                <option id="20">10</option>
                <option id="30">20</option>
            </select>
        </div>
    </div>
    <script type="text/javascript">
        //on select change, you navigate to indexAction and send the parameter maxItemPerPage
        $('#maxItemPerPage').change(function(){
            {% set currentPath = path(app.request.attributes.get('_route')) %}
            var url = "{{path(app.request.attributes.get('_route'),{'maxItemPerPage': '_itemNum'})}}";
            var item = $('#maxItemPerPage').find(":selected").text();
            jQuery(location).attr('href', url.replace('_itemNum',item ));
        });
    </script>
</div>

Я хочу извлечь и сохранить MaxItemPerPage из файла cookie, чтобы не было необходимости изменять код всех пакетов. Например, в моем контроллере я не знаю, нужно ли извлекать $maxitemperpage из файла cookie

$pagination = $paginator->paginate(
            $query,
            $this->get('request')->query->get('page', 1)/*page number*/,
            $maxItemPerPage/*limit per page*/
        );

И мне нужно изменить значение maxItemPerPage в файле cookie изменив значение html-тега с помощью javascript и перенаправив страницу на тот же контроллер, не нужно отправлять maxItemPerPage на контроллер.

Author: Community, 2014-03-10

1 answers

Это можно сделать легко (если я хорошо понял)

public function indexAction($maxItemPerPage=20)
{   
    $page_title = Util::getFormattedPageTitle("Customers");

    $em    = $this->get('doctrine.orm.entity_manager');
    $dql   = "SELECT a FROM CustomersBundle:Customer a WHERE a.enable = 1 ORDER BY a.id";
    //$query = $em->createQuery($dql);
    //$customers = $query->execute();

    $query = $em->createQuery($dql); 
    $paginator  = $this->get('knp_paginator');
    $pagination = $paginator->paginate(
        $query,
        $this->get('request')->query->get('page', 1)/*page number*/,
        $maxItemPerPage /*limit per page*/
    );


    // parameters to template
    return $this->render('CustomersBundle:Default:index.html.twig', array(
        'page_title' => $page_title,
        'pagination' => $pagination,
        'image_path' => CustomersConstants::$customers_image_thumb_path
    ));
}

В представлении

   {% extends '::base.html.twig' %}

    {% block title %}
        {{ page_title }}
    {% endblock %}
{% block javascript%}
<script type="text/javascript">

//on select change, you navigate to indexAction and send the parameter maxItemPerPage
$('#maxItemPerPage').change(function(){

var url = '{{path('controller_index_route','maxItemPerPage':_itemNum)}}';
var item = $('#maxItemPerPage').find(":selected").text();

window.location.href = url.replace('_itemNum',item );
})

</script>
    {% endblock %}

    {% block body %}
        <h1>
            {{ "customers" }}
        </h1>
        <br />
        {% for customer in pagination %}
        <a href="{{ customer.url }}" target="_blank">
            <div dir="rtl" class="st_simple_box" id="customer{{customer.id}}" >
                <table cellpadding="0" cellspacing="0" width="100%">
                    <tr>
                        <td style="vertical-align: top; width: 115px;">
                            {% if customer.imageName is not empty %}
                                <img class="newsimage" src="{{asset(image_path) ~ customer.imageName}}" alt="No Image/>
                            {% else %}
                                <img class="newsimage" src="{{asset('images/vakil_default_small.png') ~ customer.imageName}}" alt="No Image"/>
                            {% endif %}
                        </td>
                        <td style="text-align: center;">
                            <p><span style="font-family: Tahoma;">{{customer.titleFa}}</span></p>
                        </td>
                        <td style="text-align: justify;">
                            <p><span style="font-family: Tahoma;">{{customer.descriptionFa}}</span></p>
                        </td>
                    </tr>
                </table>
            </div>
        </a>
        {% endfor %}
        <div class="navigation">
            <span>
            {{ knp_pagination_render(pagination) }}
            </span>
            <!--Here is my drop down html code-->
        </div>
        <br />
<select name="maxItemPerPage" id="maxItemPerPage">
<option id="10">10</option>
<option id="20">20</option>
<option id="30">30</option>
</select>

    {% endblock %}
 2
Author: Chopchop, 2014-03-10 13:46:50