如何在crud _form中为actionUpdate添加按钮?
所以我可以删除保存的文件,并上传一个新文件
我在模型中有这个功能
public function deleteImage()
{
unlink(Yii::app()->basePath.'/../uploads/'.$this->image);
}
那么如何用这样的按钮触发呢?
<input type="button" value="delete image"/>
答案 0 :(得分:6)
在MVC中,控制器通常负责用户的交互,因此用户不会直接访问模型,而是通过控制器进行访问。控制器拦截用户操作并通过调用模型来完成工作。因此,最好不要直接调用模型函数,即使它是可能的。
现在,为了做你想做的事情,我们可以在controller中创建一个函数(动作),然后调用模型的函数。
要在控制器中调用函数(操作),我们可以关联单击按钮时将调用的URL,这可以使用onclick event来完成。我猜你不希望浏览器导航到新的url,因此我们用ajax调用这个url。
示例,1)在控制器中:
public function actionMyaction($id){
$sampleMod=SampleModel::model()->findByPk($id);
$sampleMod->deleteImage();
Yii::app()->end();
}
2)使用按钮进行查看:代替<input type="button" value="delete image"/>
使用CHtml helper class's ajaxButton。
echo CHtml::ajaxButton('Delete Image',Yii::app()->createUrl('controllername/actionname',array('id'=>$id)));
小心传递右$id
。