为了将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));
}
...
}
它渲染了“list”Twig块。我也会以同样的方式添加其他子块。这个扩展提供了比“form”块更大的自由。
我将列表扩展注册为服务:
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指导我正确的方向。
ProperyPathMapper
那样深入挖掘,一个简单的twig模板和嵌套的自定义表单类型就可以完成,这两个都在Symfony cookbook中有介绍,并在Symfony2文档中详细解释。 - Elias Van Ootegem