简体   繁体   中英

symfony2 rendering of a form as form type

I have two entities Invoice and Customer. I also have two forms InvoiceForm and CustomerForm. When I create a new Invoice (with InvoiceForm), I want to be able to also create a new Customer (just one). So here is how I do it (and it works):

<?php
namespace Acme\DemoBundle\Form;

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

class CustomerForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstname')
            ->add('lastname')
            ->add('phone');
    }

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

<?php
namespace Acme\DemoBundle\Form;

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

class InvoiceForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title')
            ->add('date')
            ->add('customer', new CustomerForm());
    }

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

So in my view (Invoice/new.html.twig) I can easily customize the way I display the attributes of my InvoiceForm (title and date), I mean I can put my form_row(invoiceForm.title) in whatever I want, I really can do anything. But for the attributes of my "subform" invoiceForm.customer, I can't, it's done automatically (firstname, lastname, phone) because all I can do is use invoiceForm.customer. Do you see what I mean?

If, in my Controller, I was making a "new CustomerForm()", and then rendering this form, I could do what I want, but since I'm making a "new InvoiceForm()", I can't. I don't know if I explain correctly ^^

Thanks for your help :)

Ok so I've found the answer by myself, actually I can access my subform attributes with:

{{ form_row(form.customer.firstname }}
{{ form_row(form.customer.lastname }}
{{ form_row(form.customer.phone }}

So I can customize as I need. And also, there is a way to test the form type in the view:

{{ form.customer.vars.block_prefixes.2 }}

which in my case will return customer_create as the name of my subform (yeah I know I did not ask for that, but I needed it too ^^ so maybe it will help someone else ;) )

Thank you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM