2016-09-08 63 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

我編輯我的答案,隨時閱讀 –