phpformssymfonysymfony-2.4

Symfony 2.4 - Adding dinamically fields in the form


I have created a form using Symfony 2.4 that is not linked to any entity because I only want to take the data to create a report. I have created a form using an AbstractType extended class and I need to add several items since the form represents a bill. I know about the allow_add attribute, but it just lets to add a field to the form and I need to do something like I show in the image:

formulario

I have no idea at all about how to do it, I have created an item class, and it contains two attributes, but I find nowhere any information about this. Until now this is what I've got:

namespace Abadia\FacturaBundle\Form;

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

class ReciboCajaType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('ciudad', 'text')
            ->add('fecha', 'date')
            ->add('valor', 'number')
            ->add('recibi_de', 'text')
            ->add('suma_recibida', 'number')
            ->add('suma_letras', 'textarea')
            ->add('bloque', 'text')
            ->add('numero', 'text')
            ->add('descripcion', 'textarea')
            ->add('areas_comunes', 'number')
            ->add('cuota_extraordinaria', 'number')
            ->add('saldo', 'number')
            ->add('cheque', 'number')
            ->add('otros', 'number')
            ->add('efectivo', 'number')
            ->add('generar', 'submit')
        ;
    }

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

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array());
    }
}

Thanks in advanced.

UPDATE: I forgot to mention that I am working with the Twig extension. Just in case knows how to do it using it.


Solution

  • Basically you will need 2 forms. One, call it main form and an another form for an item. Then you can embed the item form type into the main form type multiple times using the collection type. You will need some javascript too for adding and removing an item. It would be very long to write down exactly how to do it, but there is a good example in the docs.