我尝试制作代码系统,每篇文章都有多个代码,我是基于Symfony的文档How to Embed a collection of forms
这是我的文章实体:
<?php
namespace DEERCMS\ArticleBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Article
*
* @ORM\Table(name="article")
* @ORM\Entity(repositoryClass="PTB\ArticleBundle\Repository\ArticleRepository")
*/
class Article
{
/...
/**
* @var string
*
* @ORM\Column(name="tags", type="string", length=255)
* @ORM\ManyToMany(targetEntity="DEERCMS\ArticleBundle\Entity\Tag", cascade={"persist"})
*/
protected $tags;
public function __construct()
{
$this->date = new \DateTime();
$this->tags = new ArrayCollection();
}
public function getTags()
{
return $this->tags;
}
public function addTag(Tag $tag)
{
$tag->addTask($this);
$this->tags->add($tag);
}
public function removeTag(Tag $tag)
{
$this->tags->remove($tag);
}
/**
* Set tags
*
* @param string $tags
*
* @return Article
*/
public function setTags($tags)
{
$this->tags = $tags;
return $this;
}
}
标记实体
<?php
namespace DEERCMS\ArticleBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Tag
*
* @ORM\Table(name="tag")
* @ORM\Entity(repositoryClass="DEERCMS\ArticleBundle\Repository\TagRepository")
*/
class Tag
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
*
* @return Tag
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
}
ArticleType:
$builder
->add('title')
->add('article', TextareaType::class)
->add('img', FileType::class, array('label' => 'Zdjęcie do artykułu (img)', 'data_class' => null))
->add('tags', CollectionType::class, array(
'entry_type' => TagType::class,
'allow_add' => true,
'label' => false,
'by_reference' => false,
));
和TagType.php
$builder
->add('name', TextType::class, array(
'label' => false,
'attr' => array('class' => 'form-control', 'placeholder' => 'nazwa tagu')
))
;
当我向数据库添加文章时,Tag列如下所示:
Doctrine\Common\Collections\ArrayCollection@0000000052786f600000000016ee1beb
表格标签为空。当我试图编辑文章时出现错误
警告:为foreach()提供的参数无效
$originalTags = new ArrayCollection();
foreach ($article->getTags() as $tag) {
$originalTags->add($tag);
}
那么这段代码有什么问题?我已经试图找到解决方案好几天仍然没有进展