【问题标题】:Empty collection field type in a form表单中的空集合字段类型
【发布时间】:2014-01-09 20:14:15
【问题描述】:

我定义了一个只有一个“集合”类型字段的表单:

<?php
namespace GMC\AccesoSistemaBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use GMC\AccesoSistemaBundle\Form\FuncionType;

class FuncionesType Extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options) {

        $builder
                ->add('funciones', 'collection', array(
                    'type' => new FuncionType(),
                    'allow_add' => true,
                    'allow_delete' => true,
                    'by_reference' => false));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver) {

        $resolver->setDefaults(array(
            'data_class' => null
        ));
    }

    public function getName() {

        return 'gmc_accesosistemabundle_funcionestype';
    }

然后我在我的控制器中创建一个表单:

public function mostrarFuncionesAction() {
    $em = $this->getDoctrine()->getManager();
    $funciones = $em->getRepository('AccesoSistemaBundle:Funcion')->findAll();
    $formulario = $this->createForm(new FuncionesType(), $funciones);
    return $this->render(
            'AccesoSistemaBundle:Default:funciones.html.twig',
            array('formulario' => $formulario->createView())
            );
}

但是即使 $funciones 有两条记录,表单的 'funciones' 集合也是空的,为什么?我错过了什么吗?

如您所见,我是 Symfony2 的新手,所以请耐心等待。

提前感谢您的帮助!

【问题讨论】:

    标签: forms symfony collections


    【解决方案1】:

    Symfony 对您当前代码的作用是:

    • 获取 $functiones 对象(Function 类的实例)
    • 在 Function 类中查找名为 functiones 的属性
    • 使用此属性中的数据补充您的表单

    如果你想使用实体映射,你必须将你的表单字段($builder-&gt;add('&lt;name_here&gt;'))命名为你的函数类的一个属性,它是Function的集合。

    否则,您可以尝试使用数组来水合您的表单,给出:

    $formulario = $this->createForm(new FuncionesType(), array('functiones' => $funciones));
    

    【讨论】:

    • 您的解决方案就像一个魅力地图。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多