《PHP教程:Yii不依賴Model的表單生成器用法實例》要點:
本文介紹了PHP教程:Yii不依賴Model的表單生成器用法實例,希望對您有用。如果有疑問,可以聯系我們。
本文實例講述了Yii不依賴Model的表單生成器用法.分享給大家供大家參考.具體實現辦法如下:PHP實例
默認的Yii的表單生成器只需要這樣就可以了:
PHP實例
代碼如下:
$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件事:PHP實例
1.繼承CFormInputElement覆蓋renderLabel辦法,將label顯示成自己配置的element的labelPHP實例
2.繼承CForm覆蓋renderElement辦法,$element instanceof UCFormInputElement,并覆蓋render辦法,將Elements和getButtons循環輸出
直接上代碼:
app/protected/extensions/UCForm.php
PHP實例
代碼如下:
<?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 style="visibility:hidden">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 '';
?}
}
再來個簡單的調用示例:
代碼如下:
<?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'));
?}
}
希望本文所述對大家基于Yii框架的PHP程序設計有所贊助.PHP實例
維易PHP培訓學院每天發布《PHP教程:Yii不依賴Model的表單生成器用法實例》等實戰技能,PHP、MYSQL、LINUX、APP、JS,CSS全面培養人才。
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/13459.html