1

I have related two related entities: Magazine and Issue with a OneToMany relationship. How can I create a form to add a new Issue entity related to a specific Magazine?

When I create a form in the controller, calling it from the form class to add an Issue, how can I pass it a pre-established value for some of its fields?

I know this have to be easy, but I'm stuck here.

3 Answers 3

1

You have multiple options:

Hidden field:

You could add a hidden field to your FormType and pass e.g. the Magazine ID like that. You can checkout this tutorial as an example.

In detail it should look like this in your FormType:

$builder->add('magazine', 'entity' /*, more options... */);

And in your Controller:

$magazine = // get Your magazine here...
$issue = new Issue();
$issue->setMagazine($magazine);
$form = $this->createForm(new YourFormType(), $issue);

In the route:

You could simply generate a route like this: /magazines/{magazine_id}/issues/add
This would give you the Magazine entity in your Controller Action like so:

public function addAction($magazineId)
{
    $magazine = // get by $magazineId
    // generate your issue form and stuff

    if ($form->isValid()) {
        $issue->setMagazine($magazine);
    }
}

And you could work from there on.

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

1 Comment

Thanks, this solved It, I hadn't thought of setting some fields before calling the form.
0

If you want to bind Magazine entity to the new Issue entity, you will have to add a field with entity type in your form (with the formBuilder).

$builder->add('magazine', 'entity', array(
'class' => 'AcmeBundle:Magazine',
'property' => 'title'));

See the doc about entity field in form.

Comments

0

You can approach your problem in two separate ways.

1 - Routes : Did you setup a different route for adding an issue to each magazine?

In your controller you can do something like:

if ($form->isValid()) {
    ...
    $magazine = $this->getManager()
                     ->getRepository('AcmeBundle:Magazine')
                     ->findOneBy($magazineId); // /{magazineId}/issue/new
    ...
    $issue->setMagazine($magazine);
    $em->persist($issue);
    ...
}

Also you can read the docs for route parameters.

2 - Single Form: If you add a new issue in the same route /issue/new

When adding your Issue fields to the $formBuilder add a dropdown list to asign the Magazine

$builder->add('magazine', 'entity', array(
    'class' => 'BundleNamespace:Magazine',
    //If your class does not have a __toString() method add below
    'property' => 'title',
));

Comments

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.