如何在不调用控制器的情况下在模型中执行函数,YII 框架 [英] how to make a function execute in model without calling in controller ,YII framework
问题描述
在我基于 yii 的示例项目中,我有一个名为 gateway 的模型,该模型有一个来自 DB 的变量,名称为 $time,这是网关的创建时间来自 php time() 函数.
In my yii based sample project I have a model named gateway and this model has a variable from DB with name $time that is a creation time for gateway that comes from php time() function.
我想将此变量更改为可读形式以显示在视图中(而不是保存在数据库中)为此我编写了一个函数 setTime() 并定义了一个变量 $readabletime
I want to change this variable to a readable form to show in view (not to save in DB) and for this I wrote a function setTime() and defined a variable $readabletime
我没有在控制器中调用函数settime(),而是在模型的rules()
I didn't call function settime() in controller but in rules() of model
我写了这一行:
array('time','setTime')
但它不起作用
如何使函数在模型中工作?
How can I make a function work in model?
这是我的模型
<?php
class UserGateway extends CActiveRecord
{
public $readabletime;
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'user_gateway';
}
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('name, url, ip, time, userid, gatewaycategoryid', 'required'),
array('time, status, userid, gatewaycategoryid, defaultgateway', 'numerical', 'integerOnly'=>true),
array('name, url', 'length', 'max'=>120),
array('ip', 'length', 'max'=>18),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, name, url, ip, time, status, userid, gatewaycategoryid, defaultgateway', 'safe', 'on'=>'search'),
array('time','setTime')
);
}
public function setTime()
{
$this->readabletime=date('m/d/Y H:i:s', $this->time);
}
}
这是我的观点:
<?php echo CHtml::link('Advanced Search','#',array('class'=>'search- button')); ?>
<div class="search-form" style="display:none">
</div><!-- search-form -->
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'UserAccountnumber-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'name',
'url',
'ip',
'readabletime',
array(
'class'=>'CButtonColumn',
'buttons'=>array(
'update' => array(
'url'=>'Yii::app()->createUrl(\'User/UpdateGateway\',array(\'id\'=>$data[id]))'),
'delete' => array(
'url'=>'Yii::app()->createUrl(\'User/DeleteGateway\',array(\'id\'=>$data[id]))'
), ),
)
)
)
);
?>
谢谢大家的回答
推荐答案
你可以在你的模型中编写 afterFind
函数:
You could just write afterFind
function in your model:
protected function afterFind()
{
// convert to readable time format while viewing
$this->readabletime = date('m/d/Y H:i:s', $this->time);
parent::afterFind();
}
这样,无论在何处使用 readabletime
,它都会将其转换为您想要的格式.CActiveRecord afterFind
This way wherever readabletime
is used, it will convert it to your desired format. CActiveRecord afterFind
这篇关于如何在不调用控制器的情况下在模型中执行函数,YII 框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!