您好,登錄后才能下訂單哦!
使用Yii怎么實(shí)現(xiàn)一個(gè)表單生成器?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
具體實(shí)現(xiàn)方法如下:
默認(rèn)的Yii的表單生成器只需要這樣就可以了:
復(fù)制代碼 代碼如下:
$form = new CForm('application.views.site.loginForm', $model);
這里的application.views.site.loginForm也可以是配置數(shù)組。但是如果$model參數(shù)不傳的話是會(huì)報(bào)錯(cuò)的:Fatal error: Call to a member function isAttributeSafe()
比如我要生成一個(gè)組表單,但是我不想依賴于model,根據(jù)配置就可以生成一組表單該怎么辦,
默認(rèn)生成的表單的label是根據(jù)$model->attributes來顯示的,所以我做了2件事:
1.繼承CFormInputElement覆蓋renderLabel方法,將label顯示成自己配置的element的label
2.繼承CForm覆蓋renderElement方法,$element instanceof UCFormInputElement,并覆蓋render方法,將Elements和getButtons循環(huán)輸出
直接上代碼:
app/protected/extensions/UCForm.php
復(fù)制代碼 代碼如下:
<?php
/**
* @author Ryan <yuansir@live.cn/yuansir-web.com>
*/
class UCForm extends CForm
{
public function render()
{
$output = $this->renderBegin();
foreach ($this->getElements() as $element)
{
$output .= $element->render();
}
foreach ($this->getButtons() as $button)
{
$output .= $button->render();
}
$output .= $this->renderEnd();
return $output;
}
public function renderElement($element)
{
if (is_string($element))
{
if (($e = $this[$element]) === null && ($e = $this->getButtons()->itemAt($element)) === null)
return $element;
else
$element = $e;
}
if ($element->getVisible())
{
//UCFormInputElement 代替 CFormInputElement
if ($element instanceof UCFormInputElement)
{
if ($element->type === 'hidden')
return "<div >n" . $element->render() . "</div>n";
else
return "<div class="row field_{$element->name}">n" . $element->render() . "</div>n";
}
else if ($element instanceof CFormButtonElement)
return $element->render() . "n";
else
return $element->render();
}
return '';
}
}
再來個(gè)簡單的調(diào)用示例:
復(fù)制代碼 代碼如下:
<?php
/**
* @author Ryan <yuansir@live.cn/yuansir-web.com>
*/
class PlayerSearchController extends Controller
{
public function actionIndex()
{
$config = array(
'class' => 'ddd',
'action'=>'',
'elements' => array(
'<br><br>',
'username' => array(
'label'=>'用戶名啊',//注意這里的label
'type' => 'text',
'maxlength' => 32,
'value' => ''
),
'<br><br>',
'password' => array(
'label'=>'昵稱啊',//注意這里的label
'type' => 'password',
'maxlength' => 32,
'value' => ''
),
),
'buttons' => array(
'login' => array(
'type' => 'submit',
'label' => 'Login',
),
),
);
$model = new CFormModel();
$form = new UCForm($config, $model);
$this->render('index', compact('form'));
}
}
看完上述內(nèi)容,你們掌握使用Yii怎么實(shí)現(xiàn)一個(gè)表單生成器的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。