-->

在表单空集字段类型(Empty collection field type in a form)

2019-10-19 04:55发布

我定义的形式,只有一个“收集”类型的字段:

<?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中一个完整的newbbie所以请耐心等待我。

在此先感谢您的帮助!

Answer 1:

什么Symfony的与您当前的代码做的是:

  • 采取$ functiones对象(Function类的实例)
  • 寻找一个属性,叫做functiones在功能类
  • 滋润你的形式与这个属性中找到数据

如果你想使用一个实体mappin,你必须命名您的表单字段( $builder->add('<name_here>')作为功能类,它是集合的属性Function

否则,你可以尝试用一个数组来滋润你的单,写明:

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


文章来源: Empty collection field type in a form