2015-12-17 14 views
4

我有一個單選按鈕形式:如何在ZF2表單中製作自定義的Radio-Button標籤?

$this->add([ 
    'name' => 'time', 
    'options' => [ 
     'value_options' => [ 
      '0' => '9:00 - 12:00', 
      '1' => '12:00 - 16:00', 
      '2' => '16:00 - 19:00', 
     ], 
     'label_attributes' => [ 
      'class' => 'WW_OBJ_fm-label', 
     ] 
    ], 
    'type' => 'Radio' 
]); 

在視圖我作出這樣的輸出:

<div> 
<?php echo $this->formElement($form->get('time')); ?> 
</div> 

,並得到輸出(格式化的可讀性):

<div> 
    <label class="WW_OBJ_fm-label"> 
     <input type="radio" name="time" value="0"/> 
     9:00 - 12:00 
    </label> 
    <label class="WW_OBJ_fm-label"> 
     <input type="radio" name="time" value="1"/> 
     12:00 - 16:00 
    </label> 
    <label class="WW_OBJ_fm-label"> 
     <input type="radio" name="time" value="2"/> 
     16:00 - 19:00 
    </label> 
</div> 

但我需要,該標籤文本ist包裝<span>

<div> 
    <label class="WW_OBJ_fm-label"> 
     <input type="radio" name="time" value="0"/> 
     <span class="WW_label-text">9:00 - 12:00</span> 
    </label> 
    <label class="WW_OBJ_fm-label"> 
     <input type="radio" name="time" value="1"/> 
     <span class="WW_label-text">12:00 - 16:00</span> 
    </label> 
    <label class="WW_OBJ_fm-label"> 
     <input type="radio" name="time" value="2"/> 
     <span class="WW_label-text">16:00 - 19:00</span> 
    </label> 
</div> 

實現它的最好方法是什麼?

回答

0

我看到你的問題,有三種可能的解決方案。

1)擴大Zend\Form\View\Helper\FormRadio類,覆蓋了renderOptions方法,複製幾乎完全是一個你可以在Zend\Form\View\Helper\FormMultiCheckbox找到,但也許增加一個選項,可選屬性傳遞到span元素

2)非常微妙,但可以節省您編寫一些代碼:使用翻譯器。由於無線電值選項被翻譯,你可以保持在配置中定義,但在TRANSATION

3)不要使用$this->formElement顯示元素加入span元素你的價值觀,但實際上寫所有的HTML

+0

我已經做了你在解決方案3中寫的內容。我個人比較喜歡解決方案1,但許多重複代碼對我來說並不是很有吸引力。 –

+0

@GennadiyLitvinyuk我同意你的觀點,儘管它只是一種方法......其他的可能性是稍微重構一下,然後對Zend的人做一個pull請求,但是這肯定需要一些時間 – marcosh

0

一個解決方案是使用labelOption 'disable_html_escape':

$this->add([ 
     'name' => 'time', 
     'options' => [ 
      'value_options' => [ 
       '0' => '<span class="WW_label-text">9:00 - 12:00</span>', 
       '1' => '<span class="WW_label-text">12:00 - 16:00</span>', 
       '2' => '<span class="WW_label-text">16:00 - 19:00</span>', 
      ], 
      'label_attributes' => [ 
       'class' => 'WW_OBJ_fm-label', 
      ] 
     ], 
     'type' => 'Radio' 
    ]); 
$element = $this->get('time'); 
$element->setLabelOptions(['disable_html_escape' => true]); 
+0

不幸這個解決方案不是無法實現的,因爲值選項的標籤稍後將用於評估表單值。 –

相關問題