yii2.0用gii自动补全代码做的简单增删改查,以及图片上传和展示

首先已经用gii根据model层生成了控制器,模型,视图层。

表结构为如图所示:表名为zhoukao1,

controllers层里:Zhoukao1Controller.php

  1 <?php
  2 namespace frontendcontrollers;
  3 
  4 use Yii;
  5 use appmodelshoukao1;
  6 use appmodelsUploadForm;
  7 use appmodelssearchhoukaoSearch;
  8 use yiiwebController;
  9 use yiiwebNotFoundHttpException;
 10 use yiifiltersVerbFilter;
 11 use yiiwebUploadedFile;
 12 /**
 13  * Zhoukao1Controller implements the CRUD actions for Zhoukao1 model.
 14  */
 15 class Zhoukao1Controller extends Controller
 16 {
 17     /**
 18      * @inheritdoc
 19      */
 20     public function behaviors()
 21     {
 22         return [
 23             'verbs' => [
 24                 'class' => VerbFilter::className(),
 25                 'actions' => [
 26                     'delete' => ['POST'],
 27                 ],
 28             ],
 29         ];
 30     }
 31 
 32     /**
 33      * Lists all Zhoukao1 models.
 34      * @return mixed
 35      */
 36     public function actionIndex()
 37     {
 38         $searchModel = new ZhoukaoSearch();
 39         $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
 40        
 41         //print_r($model);die;
 42         return $this->render('index', [
 43             'searchModel' => $searchModel,
 44             'dataProvider' => $dataProvider,
 45            
 46         ]);
 47     }
 48 
 49     /**
 50      * Displays a single Zhoukao1 model.
 51      * @param integer $id
 52      * @return mixed
 53      */
 54     public function actionView($id)
 55     {
 56         return $this->render('view', [
 57             'model' => $this->findModel($id),
 58         ]);
 59     }
 60 
 61    
 62     /**
 63      * Creates a new News model.
 64      * If creation is successful, the browser will be redirected to the 'view' page.
 65      * @return mixed
 66      */
 67     public function actionCreate()
 68     {   //实例化了一个上传model和表model
 69         $model = new Zhoukao1();
 70         $upload_model = new UploadForm();
 71         //判断是否是post传值
 72         if (Yii::$app->request->isPost) {
 73            $post=Yii::$app->request->post();
 74             /*$data=['name'=>$post['Zhoukao1']['name'],
 75                 'price'=>$post['Zhoukao1']['price'],
 76                 'address'=>$post['Zhoukao1']['address'],
 77                 'tuijain'=>$post['Zhoukao1']['tuijain'],
 78             ];*/
 79             $upload_model->file = yiiwebUploadedFile::getInstance($upload_model, 'file');
 80             if ($upload_model->file && $upload_model->validate()) {
 81                 $filename='uploads/' . $upload_model->file->baseName . '.' . $upload_model->file->extension;
 82                  $upload_model->file->saveAs($filename);
 83                 /* $data['file']=$filename;*/
 84                  $post['Zhoukao1']['file']=$filename;
 85             }
 86             
 87             //model层自定义一个方法,下面是另一种方法
 88             /*$a=$model->create1($data);
 89             if ($model->load($post)&&$model->save()) {
 90              return $this->redirect(['view', 'id' => $model->id]);
 91             }*/
 92             if ($model->load($post)&&$model->save()) {
 93              return $this->redirect(['view', 'id' => $model->id]);
 94             }
 95         }else {
 96             //echo 1;die;
 97             return $this->render('create', [
 98                 'model' => $model,
 99                 'upload_model'=>$upload_model,
100             ]);
101          }
102         
103     }
104     /**
105      * Updates an existing Zhoukao1 model.
106      * If update is successful, the browser will be redirected to the 'view' page.
107      * @param integer $id
108      * @return mixed
109      */
110     public function actionUpdate($id)
111     {
112         $model = $this->findModel($id);
113 
114         if ($model->load(Yii::$app->request->post()) && $model->save()) {
115             return $this->redirect(['view', 'id' => $model->id]);
116         } else {
117             return $this->render('update', [
118                 'model' => $model,
119             ]);
120         }
121     }
122 
123     /**
124      * Deletes an existing Zhoukao1 model.
125      * If deletion is successful, the browser will be redirected to the 'index' page.
126      * @param integer $id
127      * @return mixed
128      */
129     public function actionDelete($id)
130     {
131         $this->findModel($id)->delete();
132 
133         return $this->redirect(['index']);
134     }
135 
136     /**
137      * Finds the Zhoukao1 model based on its primary key value.
138      * If the model is not found, a 404 HTTP exception will be thrown.
139      * @param integer $id
140      * @return Zhoukao1 the loaded model
141      * @throws NotFoundHttpException if the model cannot be found
142      */
143     protected function findModel($id)
144     {
145         if (($model = Zhoukao1::findOne($id)) !== null) {
146             return $model;
147         } else {
148             throw new NotFoundHttpException('The requested page does not exist.');
149         }
150     }
151 }

models层:分为两个,一个上传图片UploadFrom.php和Zhoukao1.php

UploadFrom.php代码如下:

 1 <?php
 2     namespace appmodels;
 3     use yiiaseModel;
 4     use yiiwebUploadedFile;
 5     /**
 6     * UploadForm is the model behind the upload form.
 7     */
 8     class UploadForm extends Model
 9     {
10         /**
11          * @var UploadedFile file attribute
12          */
13         public $file;
14         /**
15          * @return array the validation rules.
16          */
17         public function rules()
18         {
19             return [
20                 [['file'], 'file'],
21             ];
22         }
23     }

Zhoukao1.php代码如下:(注意rules规则里字段或多或少都需要设置一下,否则接不到值。)

 1 <?php
 2 namespace appmodels;
 3 use Yii;
 4 /**
 5  * This is the model class for table "zhoukao1".
 6  *
 7  * @property integer $id
 8  * @property string $name
 9  * @property string $price
10  * @property string $address
11  * @property integer $tuijain
12  */
13 class Zhoukao1 extends yiidbActiveRecord
14 {
15     /**
16      * @inheritdoc
17      */
18     public static function tableName()
19     {
20         return 'zhoukao1';
21     }
22     //自定义一个插入方法
23    public function create1($data)//AR模式1
24     {
25          
26         $this->setAttributes($data);//载入数据
27         return $this->insert();//返回结果
28          
29     } 
30 
31     /**
32      * @inheritdoc
33      */
34     public function rules()
35     {
36         return [
37             [['name'], 'required'],
38             [['price'], 'number'],
39             [['tuijain'], 'integer'],
40             [['name', 'address'], 'string', 'max' => 255],
41             [['file'],'string','max' => 255]
42 
43         ];
44     }
45 
46     /**
47      * @inheritdoc
48      */
49     public function attributeLabels()
50     {
51         return [
52             'id' => 'ID',
53             'name' => 'Name',
54             'price' => 'Price',
55             'address' => 'Address',
56             'tuijain' => 'Tuijain',
57             'file' => 'File',
58         ];
59     }
60 }

ZhoukaoSearch.php:搜索model(一般单独放置到models/search文件夹里)

<?php
namespace appmodelssearch;
use Yii;
use yiiaseModel;
use yiidataActiveDataProvider;
use appmodelshoukao1;
/**
 * ZhoukaoSearch represents the model behind the search form about `appmodelshoukao1`.
 */
class ZhoukaoSearch extends Zhoukao1
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'tuijain'], 'integer'],
            [['name', 'address'], 'safe'],
            [['price'], 'number'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Zhoukao1::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'price' => $this->price,
            'tuijain' => $this->tuijain,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'address', $this->address]);

        return $dataProvider;
    }
}

 接下来该views层了:

form.php里记得带文件上传头部:

 1 <?php
 2 use yiihelpersHtml;
 3 use yiiwidgetsActiveForm;
 4 /* @var $this yiiwebView */
 5 /* @var $model appmodelshoukao1 */
 6 /* @var $form yiiwidgetsActiveForm */
 7 ?>
 8 
 9 <div class="zhoukao1-form">
10 
11     <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
12 
13     <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
14 
15     <?= $form->field($model, 'price')->textInput(['maxlength' => true]) ?>
16 
17     <?= $form->field($model, 'address')->textInput(['maxlength' => true]) ?>
18 
19     <?= $form->field($model, 'tuijain')->textInput() ?>
20 
21    <?= $form->field($upload_model, 'file')->fileInput() ?>
22 
23     <div class="form-group">
24         <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
25     </div>
26 
27     <?php ActiveForm::end(); ?>
28 
29 </div>

create.php里

 1 <?php
 2 use yiihelpersHtml;
 3 /* @var $this yiiwebView */
 4 /* @var $model appmodelshoukao1 */
 5 $this->title = 'Create Zhoukao1';
 6 $this->params['breadcrumbs'][] = ['label' => 'Zhoukao1s', 'url' => ['index']];
 7 $this->params['breadcrumbs'][] = $this->title;
 8 ?>
 9 <div class="zhoukao1-create">
10     <?= $this->render('_form', [
11         'model' => $model,
12         'upload_model' => $upload_model,//记得加上上传model,否则报错找不到。
13     ]) ?>
14 
15 </div>

index.php展示页

 1 <?php
 2 use yiihelpersHtml;
 3 use yiigridGridView;
 4 /* @var $this yiiwebView */
 5 /* @var $searchModel appmodelssearchhoukaoSearch */
 6 /* @var $dataProvider yiidataActiveDataProvider */
 7 $this->title = 'Zhoukao1s';
 8 $this->params['breadcrumbs'][] = $this->title;
 9 ?>
10 <div class="zhoukao1-index">
11 
12     <h1><?= Html::encode($this->title) ?></h1>
13     <?php // echo $this->render('_search', ['model' => $searchModel]); ?>
14 
15     <p>
16         <?= Html::a('创建', ['create'], ['class' => 'btn btn-success']) ?>
17     </p>
18     <?= GridView::widget([
19         'dataProvider' => $dataProvider,
20         'filterModel' => $searchModel,
21         
22         'columns' => [
23             ['class' => 'yiigridSerialColumn'],
24 
25             'id',
26             'name'=>[//固定格式
                  'attribute'=>'string',
                  'format'=>'raw',
                  'value'=>function($model){
                      return '*'.substr("$model->name",3);
                  }
          ],
              'tel'=>[
                  'attribute'=>'string',
                  'format'=>'raw',
                  'value'=>function($model){
                      return substr("$model->tel",0,3).'****'.substr("$model->tel",-4);
                  }
          ], 27 'price', 28 'address:ntext', 29 'tuijain', 30 ['attribute'=>'file', //我的图片字段是file,还有一种显示方法为‘file:image’ ,但是图片大小不能控制。 31 'format' => ['image',['width'=>'50','height'=>'30',]], 32 ],//这是展示图片的 33 [//自定义按钮
                'class' => 'yiigridActionColumn',
                'template' => '{view} {update}',
                'header' => '操作',
                'buttons' => [
                'view' => function ($url, $model, $key) {
                    return Html::a('查看', $url, ['title' => '获取xxx'] );
                   },
                  ],
              ], 34 ['class' => 'yiigridActionColumn'], 35 ], 36 ]); ?> 37 </div>

其他的页面都是gii自动生成的代码。


注:本文由王智磊(王大宝儿)整理编写,也参考借鉴了很多大神的笔记,分享代码,分享成功,欢迎各位交流和转载,转载请注明出处(博客园:王大宝儿)http://www.cnblogs.com/wangzhilei/

原文地址:https://www.cnblogs.com/wangzhilei/p/6559142.html