当前,我有文章和标签两个表。我正在尝试在文章表单上自动填充“标签”表单元素作为选择框。从数据库表中设置标签选择框的值选项,然后在“bind”方法调用期间自动绑定文章数据,这是最好的方法吗?
Article.php
<?php
// Article class
class Article {
/**
*
* @var \Doctrine\Common\Collections\Collection|Tag[]
*
* @ORM\ManyToMany(targetEntity="Tag", inversedBy="articles")
* @Orm\JoinTable(name="rel_article_tag", joinColumns={@ORM\JoinColumn(name="article_id", referencedColumnName="article_id")}, inverseJoinColumns={@ORM\JoinColumn(name="tag_id", referencedColumnName="tag_id")})
*
* @Form\Required(false)
* @Form\Type("Zend\Form\Element\Select")
* @Form\Options({"label":"Tags: ")
* @Form\Attributes({"id":"tags", "data-placeholder":"Choose tags...", "multiple" : "multiple", "class" : "chosen-select"})
*/
private $tags;
public function __construct()
{
$this->tags = new ArrayCollection();
}
public function getTags()
{
return $this->tags;
}
public function addTags($tags)
{
$this->tags = $tags;
}
public function removeTags()
{
$this->tags = new ArrayCollection();
}
}
ArticleController.php
class ArticleController{
public function editAction()
{
$builder = new AnnotationBuilder();
$form = $builder->createForm(new TblArticle());
$id = 1;
$article = $em->find('Admin\Entity\TblArticle', $id);
$form->bind($article);
}
}
我的工作内容
在ArticleController::editAction()
中,我动态地将值选项添加到表单的标签元素中。
class ArticleController
{
public function editAction()
{
$builder = new AnnotationBuilder();
$form = $builder->createForm(new TblArticle());
// add tag options to form
$sm = $this->getServiceLocator();
$em = $sm->get('Doctrine\ORM\EntityManager');
$tags = $em->getRepository('Admin\Entity\LuTag')->findAll();
$tagOptions = [null => ''];
foreach ($tags as $tag) {
$tagOptions[$tag->getTagId()] = $tag->getName();
}
$form->get('tags')->setValueOptions($tagOptions);
// end add tag options to form
$id = 1;
$article = $em->find('Admin\Entity\TblArticle', $id);
$form->bind($article);
if ($article->getTags()) {
$tagIds = array();
foreach ($article->getTags() as $tag) {
$tagIds[] = $tag->getTagId();
}
$form->get('tags')->setValue($tagIds);
}
}
}
看起来我的控制器里有太多的代码了,我知道这不是正确的做法,但我不确定该怎么做才更好。可能使用一个FormBuilder为Tag元素设置值选项会更好吗?
谢谢。