2013-06-03 84 views
0

其實我無法理解,zend framework 2如何爲表單元素生成HTML。例如,如何在Zend framework-2表單中自定義複選框組?

$others = new Element\MultiCheckbox('others'); 
$others->setLabel('Others') 
     ->setAttribute('name', 'others'); 
$others->setValueOptions(array(
    '1' => 'Contacts', 
    '2' => 'Who viewd my profile' 
)); 

此代碼生成 -

<label><input type="checkbox" value="1" name="others[]">Contacts</label> 
<label><input type="checkbox" value="2" name="others[]">Who viewd my profile</label> 

但我需要做的HTML如下 -

<input type="checkbox" value="1" name="others[]"><label>Contacts</label> 
<input type="checkbox" value="2" name="others[]"><label>Who viewd my profile</label> 

所以如果我想改變生成的HTML,怎麼能我這麼做?

+0

這可能會幫助你http://stackoverflow.com/questions/13931834/ zend-framework-2-form-element-decorators – Orangepill

+0

我已經檢查過,但仍然沒有得到checkbox組的解決方案。我可以自定義一些,但不能使用複選框組。當我寫echo $ this-> formElement($ elements ['others']);它總是生成這些代碼組。 –

+0

也許這個'$ others-> setAttribute('name','others') - > setLabel('Others');' – Amir

回答

2

對於這種功能,您需要覆蓋Zend\Form\View\Helper\MultiCheckbox或更精確的功能renderOptions()它的功能。

你會然後讓ViewHelperManager知道$this->formMultiCheckbox()應該調用你自己ViewHelper以獲得期望的結果。

不過,我想提一提的是,你試圖做的事是非常不鼓勵的。用戶應該完全可以點擊標籤!如果你要改變標記,至少這樣做:

<input type="checkbox" value="1" name="others[]" id="cbOthers1"><label for="cbOthers2">Foo</label> 
<input type="checkbox" value="2" name="others[]" id="cbOthers1"><label for="cbOthers2">Bar</label> 

永遠不要忘記你的應用程序的可用性!另一個暗示:就標籤的瀏覽器支持而言,讓標籤內的CB自動爲您提供更廣泛的受衆!然而,儘管如此,一切取決於你。反正你必須寫自己的ViewHelper

PS:ViewHelper將是很容易的,你只需要覆蓋those lines以下幾點:

switch ($labelPosition) { 
    case self::LABEL_PREPEND: 
     $template = $labelOpen . '%s'. $labelClose .'%s'; 
     $markup = sprintf($template, $label, $input); 
    break; 
    case self::LABEL_APPEND: 
    default: 
     $template = '%s' . $labelOpen . '%s'. $labelClose; 
     $markup = sprintf($template, $input, $label); 
     break; 
} 
相關問題