Symfony中的子表单集合

时间:2017-09-21 07:53:52

标签: php symfony

我在Symfony 2.8中有以下表格:

        $form = $this->createFormBuilder()
        ->add('name', 'text')
        ->add('email', 'text')
        ->add('phone', 'text')
        ->add($this->createFormBuilder()
            ->create('address', 'form', array('virtual' => true))
            ->add('street', 'text')
            ->add('city', 'text')
            ->add('zip', 'text')
        )
        ->getForm();

我想在JS中动态添加地址。我可以按照以下文档添加CollectionType单个输入:https://symfony.com/doc/current/reference/forms/types/collection.html

但我想添加整个子表单地址。所以我想实现以下HTML结果:

<input name="form[address][0][street]" />
<input name="form[address][0][city]" />
<input name="form[address][0][zip]" />

不是

<input name="form[address][street][0]" />
<input name="form[address][city][0]" />
<input name="form[address][zip][0]" />

有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:0)

感谢我通过以下方式解决的评论:

class Address
{
    private $street;
    private $city;

    public function getStreet()
    {
        return $this->street;
    }

    public function setStreet($street)
    {
        $this->street = $street;
    }

    public function getCity()
    {
        return $this->city;
    }

    public function setCity($city)
    {
        $this->street = $city;
    }
}

class AddressType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('street', 'text')
            ->add('city', 'text');
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Address::class,
        ));
    }
}

然后在控制器中:

$data = array(
            "addresses" => array(
                0 => new Address())
        );

// $data is to show first empty subform

        $form = $this->createFormBuilder($data)
            ->add('name', 'text')
            ->add('email', 'text')
            ->add('phone', 'text')
            ->add('addresses',
                CollectionType::class,
                array(
                    'entry_type' => AddressType::class,
                    'empty_data' => true
                ))
            ->getForm();

并且twig模板看起来像这样:

{{ form_start(form) }}

    {{ form_label(form.name) }}
    {{ form_widget(form.name) }}

    {{ form_label(form.email) }}
    {{ form_widget(form.email) }}

    {% for address in form.addresses %}
         {{ form_widget(address) }}
    {% endfor %}
{{ form_end(form) }}