所以我有一个带有多个ChoiceType列表的Symfony 3表单,其中包含一些常量选项。 然后将这些选择保存在' json_array'中的数据库中(使用学说管理)。字段。
保存表单时,所选选项正确保存在数据库中:
["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,
])
以下是我在实体中定义字段的方式。
MyEntity:
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);
那么有谁能说出我错过的东西吗?
再次感谢。
答案 0 :(得分:0)
我的坏。
一切都像它应该的那样工作。
我的错误在于我的选择名称,其中包含大写字母my.Choice.1, ...
在我的getter和setter中,我将字符串强制为小写strtolower($myChoice)