我正在尝试将多选项的选项/选项耦合到数据库中的字段。在Symfony本身是否已经有了支持?
相关实体字段:
/**
* @ORM\Column(type="boolean", nullable=true)
*/
private $isSpellchecked;
/**
* @ORM\Column(type="boolean", nullable=true)
*/
private $isCompleted;
/**
* @ORM\Column(type="boolean", nullable=true)
*/
private $isEmailed;
HTML示例:
<select multiple>
<option value="isSpellchecked">Spellchecked</option>
<option value="isCompleted">Completed</option>
<option value="isEmailed">Emailed</option>
</select>
当然,我将使用Bootstrap Multiple作为select的前端实现。 问题是:如何在不在控制器中手动操作的情况下将选项连接到字段。
我是否遗漏了一些观点?
答案 0 :(得分:1)
在我看来,你必须只在你的实体中映射一个属性。
/**
* @var array
*
* @ORM\Column(type="array", nullable=true)
*/
private $myChoices;
...
public function __construct()
{
$this->myChoices = [];
}
/**
* @return array
*/
public function getMyChoices()
{
return array_unique($this->myChoices);
}
/**
* @param array $myChoices
*/
public function setMyChoices(array $myChoices)
{
$this->myChoices = [];
foreach ($myChoices as $myChoice) {
$this->addMyChoice($myChoice);
}
return $this;
}
/**
* @param string $myChoice
*/
public function addMyChoice($myChoice)
{
if (!$this->hasMyChoice($myChoice)) {
$this->myChoices[] = $myChoice;
}
return $this;
}
/**
* @param string $myChoice
*
* @return bool
*/
public function hasMyChoice($myChoice)
{
return in_array($myChoice, $this->myChoices, true);
}
在你的formType中,做一个经典:
->add('myChoices', ChoiceType::class, [
'choices' => [
'Spellchecked',
'Completed',
'Emailed',
],
'expanded' => true,
'multiple' => true,
])
然后,您的选择将作为数组保存在数据库中,如下所示:
mychoices field = a:2:{i:0;s:12:"Spellchecked";i:1;s:7:"Emailed";}
// which is like ['Spellchecked', 'Emailed']
你可以检索这样的数据:
$isSpellchecked = $MyEntity->hasMyChoice('Spellchecked'); // return true
$isCompleted = $MyEntity->hasMyChoice('Completed'); // return false