4

I'm relatively new to Symfony, tried searching for a solution for this problem but wasn't able to find any. I'm trying to get a user (in the front end) add form fields to a form.

I'm making an app where users can post recipes and the user should be able to add ingredient form fields to the form, I know how to do this in plain html & jQuery but I havn't got a clue how I can manage it in Symfony.

This is how I'm currently building forms:

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('username', 'text');
        $builder->add('email', 'email');
        $builder->add('password', 'repeated', array(
           'first_name'  => 'password',
           'second_name' => 'confirm',
           'type'        => 'password',
        ));
        $builder->add('address', new AddressType());
        $builder->add('Registreer', 'submit');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Acme\DemoBundle\Entity\User'
        ));
    }

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

This is the result I'd like to see, how can I achieve something like this in Symfony?

HTML

<a href="#" id="add">Add ingredient</a>
<form>
    <p><input type="text" name="ingredient[]" /></p>
</form>

jQuery

$(function(){

    console.log('ready')

    $('#add').click(function(){
        $('form').append('<p><input type="text" name="ingredient[]" /><a href="#" class="remove">Remove</a></p>');
    })

    $('form').on('click', '.remove', function(){
        $(this).parent().remove();
    })

})

JSFiddle

http://jsfiddle.net/MBhcF/

1

1 Answer 1

3

Ofcourse. They are called collections:

http://symfony.com/doc/current/cookbook/form/form_collections.html

You should find almost everything you need in one of my posts:

Form with a collection same entity type

If you have any questions/need help, I know collection type very well and would be glad to help you.

Sign up to request clarification or add additional context in comments.

4 Comments

Have you got a link to any example forms that use this method?
Yes, what file do you need? A php form class, twig template,...?
Not looking for a file, I'm just wonderin if you got a working demo out there somewhere?
I have a working example in my projects, but it is not public. Trust me, I did a lot of collection work so far and I believe this is one of the best ways to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.