Yii不依赖Model的表单生成器用法实例_php实例
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Yii不依赖Model的表单生成器用法实例_php实例,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2288字,纯文字阅读大概需要4分钟。
内容图文
![Yii不依赖Model的表单生成器用法实例_php实例](/upload/InfoBanner/zyjiaocheng/233/e8c26fa94bb14b679e07cb10a9191407.jpg)
默认的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 <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 "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 <yuansir@live.cn/yuansir-web.com>
*/
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程序设计有所帮助。
内容总结
以上是互联网集市为您收集整理的Yii不依赖Model的表单生成器用法实例_php实例全部内容,希望文章能够帮你解决Yii不依赖Model的表单生成器用法实例_php实例所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。