Yii不依賴Model的表單產生器用法執行個體_php執行個體

來源:互聯網
上載者:User
本文執行個體講述了Yii不依賴Model的表單產生器用法。分享給大家供大家參考。具體實現方法如下:

預設的Yii的表單產生器只需要這樣就可以了:
複製代碼 代碼如下:$form = new CForm('application.views.site.loginForm', $model);
這裡的application.views.site.loginForm也可以是配置數組。但是如果$model參數不傳的話是會報錯的:Fatal error: Call to a member function isAttributeSafe()
比如我要產生一個組表單,但是我不想依賴於model,根據配置就可以產生一組表單該怎麼辦,

預設產生的表單的label是根據$model->attributes來顯示的,所以我做了2件事:

1.繼承CFormInputElement覆蓋renderLabel方法,將label顯示成自己配置的element的label

2.繼承CForm覆蓋renderElement方法,$element instanceof UCFormInputElement,並覆蓋render方法,將Elements和getButtons迴圈輸出
直接上代碼:
app/protected/extensions/UCForm.php
複製代碼 代碼如下:<?php
/**
* @author Ryan
*/
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 "n" . $element->render() . "n";
else
return "name}">n" . $element->render() . "n";
}
else if ($element instanceof CFormButtonElement)
return $element->render() . "n";
else
return $element->render();
}
return '';
}
}
再來個簡單的調用樣本:
複製代碼 代碼如下:<?php
/**
* @author Ryan
*/
class PlayerSearchController extends Controller
{
public function actionIndex()
{
$config = array(
'class' => 'ddd',
'action'=>'',
'elements' => array(
'

',
'username' => array(
'label'=>'使用者名稱啊',//注意這裡的label
'type' => 'text',
'maxlength' => 32,
'value' => ''
),
'

',
'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'));
}
}

希望本文所述對大家基於Yii架構的PHP程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.