yii图片的上传修改删除,图片插件的使用,百度编辑器的使用,以及数据的增删改查



//1.数据模型


<?php 
	namespace backend\models;
	
	use Yii;
	use yii\db\ActiveRecord;
	
	class Shop extends ActiveRecord{
		public $imageFile;
		public static function tableName(){
			return 'shop';
		}
		public function rules(){
			return [
				['name','required','message'=>'产品名不能为空','on'=>['add']],
				['des','required','message'=>'描述不能为空','on'=>['add']],
				['txt','required','message'=>'产品说明不能为空','on'=>['add']],
				['img','required','message'=>'产品图片不能为空','on'=>['add']],
				['order','required','message'=>'排序不能为空','on'=>['add']],
				['status','required','message'=>'状态不能为空','on'=>['add']]
			];
		}
		public function attributeLabels(){
			return [
				'name'=>'产品名称',
				'des'=>'描述',
				'txt'=>'产品说明',
				'img'=>'产品图片',
				'order'=>'排序',
				'status'=>'状态'
			];
		}
		public function add($data){
			$this->scenario='add';
			$this->img=Yii::$app->session->get('imgurl');
			Yii::$app->session->set('imgurl','');
			if($this->load($data) && $this->validate()){
				if($this->save(false)){
					return 1;
				}else{
					return 0;
				}
			}else{
				return 0;
			}
		}
		public function detail($data){
			$this->scenario='add';
			$this->img=Yii::$app->session->get('imgurl');
			Yii::$app->session->set('imgurl','');
			if($this->load($data) && $this->validate()){
				if($this->save(false)){
					return 1;
				}else{
					return 0;
				}
			}else{
				return 0;
			}
		}
	}
?>


//2.图片上传模型


<?php 
	namespace backend\models;
	
	use Yii;
	use yii\base\Model;
	use yii\web\UploadedFile;
	
	class UploadForm extends Model
	{
	    /**
	     * @var UploadedFile
	     */
		public $imageFile;
	    public function rules()
	    {
	        return [
	            [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
	        ];
	    }
	    
	    public function upload($oldimg)
	    {
			// 自定义上传方法
			//文件上传路径
			$dir = "backend/web/uploads/".date("Ymd");
			// 判断文件夹是否存在,不存在时创建
			if (!is_dir($dir)) {
			    mkdir($dir, 0777, true);
			}
			if ($this->validate()) {
			    //文件名
			    $fileName = date("YmdHis").rand(9999,99999). "." . $this->imageFile->extension;
			    $dir = $dir."/". $fileName;
			    if(!$this->imageFile->saveAs($dir)){
					
			        return false;
			    }else{
					if(file_exists($oldimg)){
						unlink($oldimg);
					}
					Yii::$app->session->set('imgurl',$dir);
					return $dir;
				}
			    
			}
			// 默认的上传方法
	        // if ($this->validate()) {
	        //     $this->imageFile->saveAs('backend/web/uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
	        //     return true;
	        // } else {
	        //     return false;
	        // }
	    }
	}
?>


//3.控制器


<?php 
	namespace backend\controllers;
	
	use Yii;
	use yii\web\Controller;
	use yii\helpers\Url;
	use backend\models\Shop;
	use yii\data\Pagination;
	
	// 图片上传
	use backend\models\UploadForm;
	use yii\web\UploadedFile;
	class ShopController extends Controller{
		public $layout='mains';
		public function actionIndex(){
			$shopmodel=new Shop();
			$list = $shopmodel::find()->orderBy('creatertime DESC');
			$page = new Pagination(['totalCount' => $list->count(), 'pageSize' => 5]);
			$model = $list->limit($page->limit)->offset($page->offset)->asArray()->all();
			return $this->render('index',[
				'model'=>$model,
				'pagination'=>$page
			]);
		}
		public function actionAdd(){
			$model=new Shop();
			if(Yii::$app->request->isPost){
				$req=Yii::$app->request;
				$post=$req->post();
				// 上传图片
				$models = new UploadForm();
				$models->imageFile = UploadedFile::getInstance($model, 'imageFile');
				$resa=$models->upload();
				
				if ($resa) {
					// 文件上传成功
					// $post['img']=$resa;
				}
				// \var_dump($post);exit;	
						
				$res=$model->add($post);
				if($res){
					Yii::$app->session->setFlash('success','添加成功');
					return $this->redirect(['index']);
				}else{
					Yii::$app->session->setFlash('error','添加失败');
				}
			}
			return $this->render('add',[
				'model'=>$model
			]);
		}
		public function actionDetail(){
			$id=Yii::$app->request->get('id');
			$model=Shop::find()->where(['id'=>$id])->one();
			if(Yii::$app->request->isPost){
				$req=Yii::$app->request;
				$post=$req->post();
				// 上传图片
				$models = new UploadForm();
				$models->imageFile = UploadedFile::getInstance($model, 'imageFile');
				if($models->imageFile){
					$resa=$models->upload($model->img);
				}
				$res=$model->detail($post);
				if($res){
					Yii::$app->session->setFlash('success','修改成功');
					return $this->redirect(['index']);
				}else{
					Yii::$app->session->setFlash('error','修改失败');
				}
			}
			return $this->render('add',[
				'model'=>$model
			]);
		}
		public function actionStatus(){
			
		}
		public function actionDel(){
			
		}
	}
?>


//4.添加视图和修改视图(添加和修改视图是同一个视图add.php)


<?php 
	use yii\helpers\Url;
	use yii\widgets\ActiveForm;
	$model['status']=$model['status']==''?1:$model['status'];
?>
<link rel="stylesheet" href="/backend/web/uploadfile/css/fileinput.css">
<style>
	.btn.btn-default.kv-fileinput-upload.fileinput-upload-button{
		/* display: none; */
	}
</style>
<div class="main" style="width: 1200px;margin: 0 auto;margin-top: 100px;">
	<?php 
		$form=ActiveForm::begin([
			'options' => [
				'enctype' => 'multipart/form-data'
			],
			'fieldConfig'=>[
				'template'=>'<div class="form-group">{label}{input}{error}</div>'
			]
		]);
	?>
		<?=$form->field($model,'name')->textInput(['class'=>'form-control'])?>
		<?=$form->field($model,'order')->textInput(['class'=>'form-control'])?>
		<?=$form->field($model,'status')->radioList(['1'=>'正常','0'=>'禁止'])?>
		<?=$form->field($model,'des')->textArea(['class'=>'form-control'])?>
		<?php 
			if($model['img']){
		?>
			<div class="form-group">
				<label>预览</label><br>
				<img src="/<?=$model['img']?>" height="60" alt="">
			</div>
		<?php 
			}
		?>
		<?=$form->field($model,'imageFile')->fileInput(['id'=>'file-0'])->label('商品图片')?>
		<div class="form-group">
			<label>产品描述</label><br>
			<?=$form->field($model,'txt')->textArea(['class'=>'form-control','id'=>'describe','style'=>'display: none;'])->label(false)?>
			<!-- <textarea rows="" cols="" name="txt" id="describe" style="display: none;"></textarea> -->
			<script id="describe_a" name="describe" type="text/plain"><?=$model['txt']?>
			</script>
		</div>
		<button type="submit" onclick="getstring()" class="btn btn-default">提交</button>
	<?php 
		ActiveForm::end();
	?>
	<script src="/backend/web/uploadfile/js/jquery-2.0.3.min.js"></script>
	<script src="/backend/web/uploadfile/js/fileinput.js"></script>
	<script src="/backend/web/uploadfile/js/fileinput_locale_de.js"></script>
	<!-- 配置文件 -->
	<script type="text/javascript" src="/backend/web/ueditor/ueditor.config.js"></script>
	<!-- 编辑器源码文件 -->
	<script type="text/javascript" src="/backend/web/ueditor/ueditor.all.js"></script>
	<script>
		<!-- 实例化编辑器 -->
		var ue = UE.getEditor('describe_a');
		function getstring() {
			document.getElementById('describe').value = UE.getEditor('describe_a').getContent();
		}
		// 图片插件
		$("#file-0").fileinput({
		    'allowedFileExtensions' : ['jpg', 'png','gif'],
			'showUpload':false,
			'language': 'zh',
		});
	</script>
</div>


//5.数据展示


<?php 
	use yii\widgets\LinkPager;
	use yii\helpers\Html;
	use yii\helpers\Url;
?>

<div class="main" style="width: 1200px;margin: 0 auto;margin-top: 50px;">
	<table class="table table-condensed">
		<tr>
			<th>产品名</th>
			<th>描述</th>
			<th>图片</th>
			<th>排序</th>
			<th>状态</th>
			<th>注册时间</th>
			<th>修改时间</th>
			<th>操作</th>
		</tr>
		<?php 
			foreach($model as $key=>$val){
		?>
			<tr>
				<td><?=$val['name']?></td>
				<td><?=$val['des']?></td>
				<td><img src="/<?=$val['img']?>" height="50" alt=""></td>
				<td><?=$val['order']?></td>
				<td><?=$val['status']?></td>
				<td><?=$val['creatertime']==''?'无':date('Y-m-d',$val['creatertime'])?></td>
				<td><?=$val['creatertime']==''?'无':date('Y-m-d',$val['creatertime'])?></td>
				<td>
					<a href="<?=Url::to(['detail','id'=>$val['id']])?>" class="glyphicon glyphicon-pencil"></a>
					<a href="<?=Url::to(['del','id'=>$val['id']])?>" class="glyphicon glyphicon-trash" style="margin-left: 20px;"></a>
				</td>
			</tr>
		<?php 
			}
		?>
	</table>
	<nav aria-label="Page navigation">
		<?=
			LinkPager::widget([
				'pagination' => $pagination,
				'nextPageLabel' => '<span aria-hidden="true">&raquo;</span>',
				'prevPageLabel' => '<span aria-hidden="true">&laquo;</span>',
				'maxButtonCount' => 5,
				'options' => ['class' => 'pagination'],//自定义class
			]);
		?>
	</nav>
	
</div>
<script>
	function fun(id){
		$.get("<?=Url::to(['static'])?>",{id:id},function(data){
			dat=JSON.parse(data);
			if(dat.data=='0'){
				alert(dat.res);
			}else if(dat.data==1){
				alert(dat.res);
			}else if(dat.data==2){
				if(dat.state==1){
					$('#fun'+id).html("<button type='button' class='btn btn-success'>正常</button>");
				}else{
					$('#fun'+id).html("<button type='button' class='btn btn-danger'>禁止</button>");
				}
			}
		})
	}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原克技术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值