所以我有一个带有多个ChoiceType列表的Symfony 3表单,其中包含一些常量选项 . 然后将这些选择保存在'json_array'字段中的数据库(使用doctrine管理)中 .
保存表单时,所选选项正确保存在数据库中:
["my.Choice.1","my.Choice.2"]
但是,当我想再次编辑此表单时,没有选定的选项被“选中” . 他们保持不受限制 .
我有一个其他字段(EntityType,multiple),它正确地预先填充了数据库中的数据 .
MyEntityType :
$builder
->add('myChoices', ChoiceType::class, [
'choices' => [
'choice #1' => MyEntity::CHOICE_1,
'choice #2' => MyEntity::CHOICE_2,
],
'expanded' => true,
'multiple' => true,
])
以下是我的字段在实体中的定义方式 .
我的实力:
const CHOICE_1 = 'my.Choice.1';
const CHOICE_2 = 'my.Choice.2';
/**
* @var array
*
* @ORM\Column(name="my_choices", type="json_array", nullable=true)
*/
private $myChoices;
/**
* @return array
*/
public function getMyChoices()
{
return array_unique($this->myChoices);
}
/**
* @param array $myChoices
*
* @return MyEntity
*/
public function setMyChoices(array $myChoices)
{
$this->myChoices = [];
foreach ($myChoices as $myChoice) {
$this->addMyChoice($myChoice);
}
return $this;
}
/**
* @param string $myChoice
*
* @return MyEntity
*/
public function addMyChoice($myChoice)
{
$myChoice = strtolower($myChoice);
if (!$this->hasMyChoice($myChoice)) {
$this->myChoices[] = $myChoice;
}
return $this;
}
/**
* @param string $myChoice
*
* @return bool
*/
public function hasMyChoice($myChoice)
{
return in_array(strtolower($myChoice), $this->myChoices, true);
}
我的表单就像这样调用:
$myEntity = ..... // loaded from database
$form = $this->createForm(MyEntityType::class, $myEntity);
那么有谁能告诉我我所缺少的东西?
再次感谢 .
1 回答
我的错 .
一切都像它应该的那样工作 .
我的错误在于我的选择名称,其中包含大写字母
my.Choice.1, ...
在我的getter和setter中,我强制字符串为小写
strtolower($myChoice)