简体   繁体   中英

Add dropdown to symfony 3 form

I want to add a dropdow field for category in my form in symfony version 3, I have tried to solutions but each one have their own problem

First got all categories and pass them to my view and show them: Action:

 /**
     * Creates a new News entity.
     *
     * @Route("/new", name="news_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $news = new News();
        $form = $this->createForm('AppBundle\Form\NewsType', $news);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($news);
            $em->flush();

            return $this->redirectToRoute('news_show', array('id' => $news->getId()));
        }

        $em = $this->getDoctrine()->getManager();
        $categories = $em->getRepository('AppBundle:Category')->findAll();

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

View:

{% extends 'base.html.twig' %}

{% block body %}
    <h1>News creation</h1>

    {{ form_start(form) }}

    <label for="news_content" class="required">Category</label>
    <select name="news[categoryId]">
        {% for category in categories %}
            <option value="{{ category.id }}">{{ category.title }}</option>
        {% endfor %}
    </select>
    {{ form_widget(form) }}
        <input class="btn btn-sm btn-success" type="submit" value="Create" />

    {{ form_end(form) }}
    <ul>
        <li>
            <a class="label label-sm label-info" href="{{ path('news_index') }}">Back to the list</a>
        </li>
    </ul>
{% endblock %}

The form is created as I expected but when i want to submit it, it show an validation error as bellow:

This form should not contain extra fields.

second solution that I have tried is to generate the dropdown from my Type, so in NewsType I changed the buildForm function as bellow:

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('categoryId', EntityType::class, [
            'class' => 'AppBundle:Category',
            'choice_label' => 'title',
        ])
        ->add('title')
        ->add('content')
    ;
}

It this way, the form also have been created nicely but after submit, an database exception returned and said:

An exception occurred while executing 'INSERT INTO news (category_id, title, content) VALUES (?, ?, ?)' with params [{}, "asdf", "asdf"]:

Catchable Fatal Error: Object of class AppBundle\\Entity\\Category could not be converted to string

It mean that my category_id passed as an object !

What should I do?

BTW, my english is a little weak, please do not put and minus on my post, I had been ban multiple times.

Thanks in advance.

all symfony is trying to do is to find a string representation of the Category object, so it can populate the option fields.

you can solve this in a couple of ways:

  1. In the Category object, you can make a __toString method.

     public function __toString() { return $this->name; // or whatever field you want displayed } 

or

  1. you can tell symfony which field to use as the label for the field. From docs

     $builder->add('attending', ChoiceType::class, array( 'choices' => array( new Status(Status::YES), new Status(Status::NO), new Status(Status::MAYBE), ), 'choice_label' => 'displayName', // <-- where this is getDisplayName() on the object. )); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM