为了将Symfony表单转换为列表,我创建了一个新的表单类型ListType,它可以接受任意嵌套的集合类型。这样,我可以创建具有多个列的列表。它看起来像:
class ListType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
if (empty($options['collection_type']) || !$options['collection_type'] instanceof AbstractType) {
throw new \InvalidArgumentException();
}
$builder->add('rows', 'collection', array('type' => $options['collection_type']));
$builder->add('save', 'submit', array('label' => 'Save'));
}
...
}
我将使用$ options数组提供或打开和关闭其他功能,例如搜索过滤器和分页。
为了有一个易于使用的界面来显示列表,例如:
{{ list(list) }}
我创建了Twig扩展名:
class ListExtension extends \Twig_Extension
{
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('list', array($this, 'listFunction'), array('is_safe' => array('html'), 'needs_environment' => true))
);
}
public function listFunction(\Twig_Environment $env, FormView $form)
{
return $env->resolveTemplate($this->defaultTemplate)->renderBlock('list', array('form' => $form));
}
...
}
它呈现“列表” Twig块。我还将以相同的方式添加其他子块。与“ form”块相比,此扩展提供了更大的feedom。
我将列表扩展注册为服务:
# app/config/services.yml
services:
my.twig.list.extension:
class: MyBundle\Twig\Extension\ListExtension
arguments: ["::my_theme.html.twig"]
public: false
tags:
- { name: twig.extension }
现在,我只需要创建一种ListType形式并将其传递给行实体数组即可。
感谢Elias Van Ootegem为我指出正确的方向。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句