我想在symfony版本3的表单中为类别添加一个dropdow字段,我已经尝试过解决方案,但每个方案都有自己的问题
首先获取所有类别,并将它们传递到我的视图中,然后显示它们:行动:
/**
* 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,
));
}
视图:
{% 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 %}
表单是按照我的预期创建的,但当我想提交它时,它显示了一个验证错误,如下所示:
This form should not contain extra fields.
我尝试过的第二个解决方案是从我的Type生成下拉列表,所以在NewsType中,我更改了buildForm函数如下:
/**
* @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')
;
}
通过这种方式,表单也创建得很好,但在提交后,返回了一个数据库异常,并表示:
使用params[{},"asdf","asdf"]执行"INSERT INTO news(category_id,title,content)VALUES(?,?,?)"时发生异常:
可捕获的致命错误:类AppBundle''Entity''Category的对象无法转换为字符串
这意味着我的category_id作为对象传递!
我该怎么办?
顺便说一句,我的英语有点弱,请不要在我的帖子上加减号,我已经被封了好几次了。
提前谢谢。
symfony所要做的就是找到Category对象的字符串表示,这样它就可以填充选项字段。
你可以用两种方法来解决这个问题:
-
在Category对象中,可以创建一个
__toString
方法。public function __toString() { return $this->name; // or whatever field you want displayed }
或
-
您可以告诉symfony使用哪个字段作为字段的标签。来自文档
$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. ));