TuxMeister
TuxMeister

Reputation: 275

OneToMany relation and how to create form

I'm working on a spare-time project for my school, the main purpose is to have a pseudo social network for sharing learning resources among students.

I am using FOSUserBundle for authentication and user management. My database has a few tables that are related to each other, but the issue starts with the following:

User table with OneToMany relation to Resources table, as one user can post or own many resources.

I have created the relation in the entities, posted it to the DB server and appears to be correct, however I am wondering what would be the best way to display / handle a form for adding new resources given that the data has to be related.

I have done a similar thing adding a OneToMany relation between my Schools table and Users (as one school can hold many students), displaying an entity choice field in the registration form I modified from FOSUserBundle, and this works correctly, however I am not entirely sure of how this works as this magic is handled by the FOS bundle mostly.

I have a formType setup for the resource adding form, and I would like to know what is the best way ensuring the relation of the data once the form is submitted.

P.S. The setup is fairly straight forward. I have the FormType for Resource adding form setup, it displays correctly. I am calling it from my controller with

$newResourceForm = $this->createForm(new ResourceType(), $resource); $newResourceForm->handleRequest($request);

and then using the createView() method while rendering the template.

EDIT1: If you guys need the actual code from the different files involved, including my entities, please let me know and I will add links to some pastebins, however I think my current description of the issue would suffice.

Upvotes: 0

Views: 78

Answers (1)

Richard
Richard

Reputation: 4129

You can create a User form type and then embed your ResourceType form type in that form.

E.g. something like:

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('resources', 'collection', array('type' => new ResourceType()));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Your\Namespace\Entity\YourUserModel',
        ));
    }

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

Symfony forms are pretty flexible in how they work,I'd recommend having a read of the forms documentation

Also how to embed a collection of forms and the collection field type.

In terms of saving your data with the correct User -> Resource relations, symfony will handle that for you if you construct your form correctly & persist your entities after a valid form submission.

Upvotes: 1

Related Questions