0

I'm new to Symfony and cannot easily find Symfony 3 answers to my question.

Problem : I have a basic form setup which populates select boxes with basic id+name Entity values (Country, Company, Partner, etc.)

All the select boxes are correctly populated from the DB. However when I try saving the populated form, all the "choices" are returned as null.

Question : What am i missing to make sure the selected values in the selectboxes are sent through to the INSERT statement ?

Note : I have looked at the Form documentation but that didn't seem to cover this scenario.

Form : Populated form

Result on Submit : Submit result

Controller excerpt :

/**
 * @Route("/opportunity/add", name="add_opportunity")
 */
public function addAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();

    $opportunity = new Opportunity();
    $form = $this->createForm(OpportunityType::class, $opportunity);

    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {

        $em->persist($opportunity);
        $em->flush();

        return $this->redirectToRoute('/opportunity/add');
    }

    return $this->render(
        'opportunity/add-opportunity.html.twig',
        array('form' => $form->createView())
    );
}

Build Form from OpportunityType :

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class)

        ->add('countries', EntityType::class, array(
            'class' => 'AppBundle:Country',
            'choice_label' => 'name'
        ))

        ->add('partners', EntityType::class, array(
            'class' => 'AppBundle:Partner',
            'choice_label' => 'name'
        ))

        ->add('companies', EntityType::class, array(
            'class' => 'AppBundle:Company',
            'choice_label' => 'name'
        ))

        ->add('users', EntityType::class, array(
            'class' => 'AppBundle:User',
            'choice_label' => 'name'
        ))

        ->add('stages', EntityType::class, array(
            'class' => 'AppBundle:Stage',
            'choice_label' => 'name'
        ))

        ->add('stage_changed_date', DateType::class)
        ->add('target_close_date', DateType::class)
        ->add('contract_value', TextType::class)

    ;
}

Form twig :

{% block body %}
<div style="max-width: 600px; margin-top:100px; padding:15px; margin-left:auto; margin-right:auto;" class="card">
{{ form_start(form) }}
    <div class="form-header purple darken-4">
        <h3><i class="fa"></i>Add Opportunity</h3>
    </div>
    {{ form_row(form.name) }}
    {{ form_row(form.countries) }}
    {{ form_row(form.partners) }}
    {{ form_row(form.companies) }}
    {{ form_row(form.users) }}
    {{ form_row(form.stages) }}
    {{ form_row(form.stage_changed_date) }}
    {{ form_row(form.target_close_date) }}
    {{ form_row(form.contract_value) }}

    <button class="btn btn-raised btn-primary" type="submit">ADD</button>
{{ form_end(form) }}
</div>

{% endblock %}

3
  • How are you defining your entities and relations between them ? Commented Nov 15, 2016 at 13:49
  • At the moment all the entities are straightforward ORM table-mapped, with "id" and "name". I may be missing inter-entity relationships. But in this case, I dont need to persist other entities. The "opportunity" table stores ids of the other values. The dropdown for each has the "id" as the "value", and i want to persist that actual "id" not the Entity Country. (working insert) INSERT INTO opportunity (name, partner_id, country_id, company_id, user_id, stage_id, stage_changed_date, target_close_date, contract_value) VALUES ("Test", 1, 2, 1, 3, 1, 1, "2016-01-01", "2016-12-12) Commented Nov 15, 2016 at 14:02
  • @ChuckNorris Okay some debugging revealed that the submission result has objects for each of the dropdowns instead of the selected string value. i.e. the result has : country_id = null and countries = [object] (which has the correct selected value)` So maybe your comment about relationships is something I have to look at. I'll read up the core documentation, but any suggestions would be extremely helpful. Thanks ! Commented Nov 15, 2016 at 14:14

2 Answers 2

0

Yes, since in your formType, each of your field is an EntityType class, I think Symfony is waiting for an entity. So you have to create a realtion between entity Oppotunity and its "sub fields".

If you don't want to create relation in your entity, maybe try somthing like Symfony2 Form Builder - creating an array of choices from a DB query


Edit - adding example

You can show a working example here : https://gitlab.com/gaea44/test-form

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

3 Comments

Thanks for commenting further. I'm experimenting with those mappings now. For Opportunity (main object which has ids of the others) I've added these annotations to the foreign id fields : * @ManyToOne(targetEntity="AppBundle\Entity\Partner") * @JoinColumn(name="partner_id", referencedColumnName="id") But its still not using the entity values. Is there anything I need to add to the "reverse side" ? i.e. all the dropdown Entities ?
(for other folks) Note that the example above is for Symfony 2 and is different for Symfony 3
Its a Symfony 3 example
0

Resolved, and probably not the best solution, but something which may be helpful to others.

I ended up just assigning the values as needed on the Opportunity object after Form submission before db persistence :

$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {

    // Get selected values for dropdowns
    $opportunity->setPartnerId($opportunity->getPartners()->getId());
    $opportunity->setCountryId($opportunity->getCountries()->getId());
    $opportunity->setCompanyId($opportunity->getCompanies()->getId());
    $opportunity->setUserId($opportunity->getUsers()->getId());
    $opportunity->setStageId($opportunity->getStages()->getId());

    $em->persist($opportunity);
    $em->flush();

    return $this->redirectToRoute('add_opportunity');
}

1 Comment

Hi, I've juste added a working examle with entities relations. It allows you to have a cleaner code.

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.