在表单类型中为data_class分配值

时间:2014-06-24 20:44:14

标签: symfony

我有一个表单类型,并希望知道在下面我的案例data_class中对setDefaultOptions的内容。我知道我们通常放置实体的路径,但在这种情况下我嵌入了两个实体,所以我现在该怎么办?

我知道我们可以忽略它,但我不想,因为SensioLabs(...So, while not always necessary, it's generally a good idea to explicitly specify the data_class option...)建议不要这样做。

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

表单类型:

namespace Car\BrandBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class BothType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->setMethod('POST')
            ->setAction($options['action'])
            ->add('brands', new BrandsType())
            ->add('cars', new CarsType())
            ->add('button', 'submit', array('label' => 'Add'))
            ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array('data_class' => '?????????????????????'));
    }

    public function getName()
    {
        return 'both';
    }
} 

控制器:

namespace Car\BrandBundle\Controller;

use Car\BrandBundle\Entity\Brands;
use Car\BrandBundle\Entity\Cars;
use Car\BrandBundle\Form\Type\BothType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class BothController extends Controller
{
    public function indexAction()
    {
        $entity = array(new Brands(), new Cars());

        $form = $this->createForm(new BothType(), $entity,
                array('action' => $this->generateUrl('bothCreate')));

        return $this->render('CarBrandBundle:Default:both.html.twig',
            array('page' => 'Both', 'form' => $form->createView()));
    }
}

当我回复提交的数据时,我得到了这个复制的数据:

Array
(
    [0] => Car\BrandBundle\Entity\Brands Object
        (
            [id:protected] => 
            [name:protected] => 
            [origin:protected] => 
        )

    [1] => Car\BrandBundle\Entity\Cars Object
        (
            [id:protected] => 
            [model:protected] => 
            [price:protected] => 
        )

    [brands] => Car\BrandBundle\Entity\Brands Object
        (
            [id:protected] => 
            [name:protected] => Mercedes
            [origin:protected] => Germany
        )

    [cars] => Car\BrandBundle\Entity\Cars Object
        (
            [id:protected] => 
            [model:protected] => SL500
            [price:protected] => 25,000
        )

)

1 个答案:

答案 0 :(得分:1)

我认为这里最好的方法实际上是忽略它,因为没有特定的实体将其链接到。该文档可能应该被理解为"如果您的表单绑定到实体,则最好是#34;。