我遇到了zend2表单的问题。我创建了一个实体,它从数据库中获取一些数据并加入一些表......
这是实体:
class Campaigns
{
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
*/
protected $id;
/**
*
* @ORM\Column(name="campaign_name", type="string")
*
*/
protected $campaigns;
/**
* @var mixed
*
* @ORM\ManyToMany(targetEntity="Application\Entity\Countries", cascade={"persist"}, orphanRemoval=false)
* @ORM\JoinTable(name="campaigns_countries",
* joinColumns={@ORM\JoinColumn(name="campaign_id", referencedColumnName="id", onDelete="CASCADE")},
* inverseJoinColumns={@ORM\JoinColumn(name="country_id", referencedColumnName="id", onDelete="CASCADE")}
* )
*/
protected $countries;
此代码下面是getter和setter,构造函数,add和remove函数。
他们是:
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
return $this;
}
public function getCampaigns()
{
return $this->campaigns;
}
public function setCampaigns($campaigns)
{
$this->campaigns = $campaigns;
return $this;
}
public function addCampaigns($campaigns = null)
{
foreach ($campaigns as $c) {
if (!$this->campaigns->contains($c)) {
$this->campaigns->add($c);
}
}
}
public function removeCampaigns($campaigns)
{
foreach ($campaigns as $c) {
if ($this->campaigns->contains($c)) {
$this->campaigns->removeElement($c);
}
}
}
public function getCountries()
{
return $this->countries;
}
public function setCountries($countries)
{
$this->countries = $countries;
return $this;
}
public function addCountries($countries = null)
{
foreach ($countries as $c) {
if (!$this->countries->contains($c)) {
$this->countries->add($c);
}
}
}
public function removeCountries($countries)
{
foreach ($countries as $c) {
if ($this->countries->contains($c)) {
$this->countries->removeElement($c);
}
}
} //construct for countries
public function __construct()
{
$this->setCountries(new ArrayCollection());
}
我的问题在于protected $countries
。如果我在表单中添加属性值,它会为我提供在实体中找不到的“countries”属性。
如果我不添加它,而是使用__toString()
函数,它会给我一个错误,说它无法将国家/地区转换为字符串...在__toString()
函数中我添加了以下代码:
public function __toString()
{
return $this->countries;
}
感谢您的帮助!
AE
答案 0 :(得分:1)
您说您想要一个包含所有相关国家/地区的字符串。以下代码演示了如何实现此目的:
$campaignCountryNames = array();
$campaignCountries = $campaign->getCountries();
foreach ($campaignCountries as $country) {
// I assume your Country entity has a name property
$campaignCountryNames[] = $country->getName();
}
echo implode(', ', $campaignCountryNames);