2016-09-08 61 views
0

我试图将多选的选项/选项耦合到数据库中的字段。 Symfony本身是否已经支持?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针对前端实现选择的。 问题是:如何将选项连线到控制器中,而无需手动执行。

我错过了一些观点吗?

回答

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 
+0

谢谢查克,不过你是苏用你的解决方案将选择转换为数据库字段?是否有可能在实体上执行'getIsEmailed()'? – DelphiLynx

+0

对不起,我只是看到你的领域必须是“多个”。在这种情况下,我的回应并不准确。我编辑它以符合您的需求。 –

+0

我编辑我的答案,随时阅读 –