2016-08-12 60 views
0

Yii2 HTML::radio()幫手與標籤標籤完全外部輸入標籤單選按鈕生成html input標籤與周圍像這樣的輸入標籤標籤:如何產生yii2

<label> 
    <input type="radio" name="abc" value="1"> Hello 
</label> 

但我需要這樣的:

<input type="radio" name="abc" value="1" id="radio1"> 
<label for "radio1">Hello</label> 

它是否可以custozime這裏面radio helper

回答

0

不,你不能。從yii\helper\BaseHtml類代碼可以看出,這種嵌套標籤來自radio()方法的源代碼,無需通過更改選項進行配置。

你需要的是覆蓋該方法。這很容易。

  1. 在命名空間app\helpers中,創建類Html。並將其放入名爲/Helpers/Html.php相對於您的應用程序根一個新文件(如果你已經有了基本的Yii應用程序),並把這樣的事情裏面:

    namespace app\helpers;
use Yii; use yii\helpers\BaseHtml;
class Html extends BaseHtml { public static function radio($name, $checked = false, $options = []) { $options['checked'] = (bool) $checked; $value = array_key_exists('value', $options) ? $options['value'] : '1'; if (isset($options['uncheck'])) { // add a hidden field so that if the radio button is not selected, it still submits a value $hidden = static::hiddenInput($name, $options['uncheck']); unset($options['uncheck']); } else { $hidden = ''; } if (isset($options['label'])) { $label = $options['label']; $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : []; unset($options['label'], $options['labelOptions']); $content = static::input('radio', $name, $value, $options); $content .= static::label($label, null, $labelOptions); return $hidden . $content; } else { return $hidden . static::input('radio', $name, $value, $options); } } }

說明:

我們剛剛從yii\helpers\BaseHtml複製了radio()方法的代碼,並將包含static::label()的行改爲將static::input()的輸出與它分開;

由於原創和我們的自定義類擴展yii\helpers\BaseHtml,並且原始yii\helpers\Html未重新定義任何BaseHtml方法,所以除了無線電以外的元素的邏輯將不會丟失。

命名空間和類名稱不應該完全相同,但顯然它們應該與yii\helpers\Html不同。

  • 只是在你查看的代碼替換use yii\helpers\Html;use app\helpers\Html;
  • 就這樣!