本文实例讲述了Yii不依赖Model的表单生成器用法。分享给大家供大家参考。具体实现方法如下:
默认的Yii的表单生成器只需要这样就可以了:
代码如下:
$form = new CForm('application.views.site.loginForm', $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
代码如下:
/**
* @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";
else
return "
}
else if ($element instanceof CFormButtonElement)
return $element->render() . "n";
else
return $element->render();
}
return '';
}
}
代码如下:
/**
* @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程序设计有所帮助。