目前,我有文章和标签表.我试图自动填充"标签"表单元素作为文章表单上的选择框.从数据库表中设置标签选择框的值选项的最佳方法是什么,然后让文章在"绑定"方法调用期间自动绑定标签数据?
Article.php
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()
,我已经将值选项动态添加到表单上的tags元素.
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元素的值选项?
谢谢.