gpt4 book ai didi

forms - 使用 KnpPaginatorBundle 对 Symfony 表单集合进行分页

转载 作者:行者123 更新时间:2023-12-01 15:20:02 25 4
gpt4 key购买 nike

喜欢How to handle Symfony form collection with 500+ items我有一个很大的 symfony 表单集合。在提到的线程中,有人建议对集合使用分页。

如何使用 knpPaginatorBundle 对这样的表单集合进行分页?

表单类型是这样的

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('myType', 'collection', array(
'type' => new MyType(),
))
;
}

我的 Controller 生成一个带有集合的表单

$form = $this->createForm(new MyFormCollectionType());

然后我尝试使用分页器

$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$form['myType'],
$request->get('page', 1),
10
);

我想我对 paginate($target) 使用了错误的目标,什么是 symfony 表单集合中的正确目标?

最佳答案

Symfony3 上的例子:

目录 Controller

// I want to paginate products (my collection)
$products = $catalog->getProducts(); // ArrayCollection

// Pagination
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate($products, $request->query->getInt('page', 1), 10);

// build the form with catalog data
$form = $this->createForm(CatalogProductType::class, $catalog, array("pagination" => $pagination));

// [...]

// show page
return $this->render('catalogs/products.html.twig', array(
'catalog' => $catalog,
'form' => $form->createView(),
'pagination' => $pagination
));

目录表 (CatalogProductType)

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('products', CollectionType::class, array(
'entry_type' => ProductType::class,
'data' => $options['pagination'],
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'label' => false,
'by_reference' => false
))
->add('save', SubmitType::class, array(
'attr' => array('class' => 'button-link save'),
'label' => 'Validate'
))
;
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Catalog',
'pagination' => null // Don't forget this !
));
}

我的观点(products.html.twig)

<div class="navigation">{{ knp_pagination_render(pagination) }}</div>

{% if pagination.getTotalItemCount > 0 %}
{% for widget in form.products.children %}
{# Refers to a Twig macro #}
{{ _self.prototype_product(widget) }}
{% endfor %}
{% else %}
<div class="error">The is no product in this catalog</div>
{% endif %}

My products collection is now paginated.

关于forms - 使用 KnpPaginatorBundle 对 Symfony 表单集合进行分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28719184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com