yii2 model
每个模型对应一张表,rules方法定义对应的字段格式,长度。attributeLabels设置对应字段名的默认显示名。
yii2 form
每个nameform对应一个表单,有两个基础函数 rules和attributeLabels设置字段格式和显示名称,对用户输入的内容进行过滤以及验证。
public function rules(){
return [
[['title'], 'required','message'=>'标题不能为空'],
[['keywords'],'required','message'=>'关键字不能为空'],
['title', 'string', 'min' => 2, 'max' => 10,'tooLong'=>'不能低于2位','tooShort'=>'不能超过10位'],
];
}
上面的方法就对title字段进行验证了,而且规定了他的长度。
yii2 html
yii2的HTML文件需要事先定义yii一些自己的标签,开头定义
<?php $form = ActiveForm::begin(['id'=>'add-category']);?>
<?= $form->field($model,'title')->textInput(['class'=>'form-contrl','id'=>'cate','style'=>'width:300px;height:30px;']); ?>
<input type="submit" value="添加分类" id="da-login-submit" class="btn" />
<?php ActiveForm::end(); ?>
可在括号里面添加这个输入框的属性
yii2 url
yii2中生成url用Url组件 引入组件
use yii\helpers\Html;
生成地址链接:
$model->find()->where(['status'=>'1','code']=>'2')->select('id,title')->limit(2)->asarray()->all();
ar类使用原生sql查询
$sql = "select * from user";
$result = $model->findBysql($sql)->asarray()->all();
ar类插入数据
$document = new Document;
$model = new modelForm;//可以通过访问$model这个对象获得用户提交的表单数据
$title = $model->title;
$keywords = $model->keywords;
$content = $model->content;
$time = time();
$status = 1;
$document->title = $title;
$document->uid = 1;
$document->keywords = $keywords;
$document->content = $_POST['content'];
$document->create_time = $time;
$document->status = $status;
$result = $document->insert();
$id = $document->attributes['id'];//上次插入的id
yii2 分页
控制器端代码:
public function actionDocumentlist(){
$this->layout = 'admin';
$model = new Document;
$document_list = $model->find(array('select'=>array('id,title')))->where(['status'=>'1'])->limit(2)->select('id,title')->asarray()->all();
$query = Document::find();
$pagination = new Pagination([
'defaultPageSize' => 1,
'totalCount' => $query->count(),
]);
$countries = $query->orderBy('id')
->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('documentlist', [
'countries' => $countries,
'pagination' => $pagination,
]);
}
view层代码:
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
use yii\helpers\Url;
?>
<h1>文章列表</h1>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>标题</th>
<th>创建时间</th>
<th>操作</th>
</tr>
</thead>
<?php foreach($countries as $country): ?>
<tbody>
<tr>
<td><?=Html::encode("$country->id") ?></td>
<td><?=Html::encode("$country->title") ?></td>
<td><?=Html::encode("$country->create_time") ?></td>
<td><a href="">删除</a> <a href="">修改</a>
<?php
if($country->status == 1){
echo '<a href="">禁用</a>';
}else{
echo '<a href="">启用</a>';
}
?>
</td>
</tr>
<?php endforeach;?>
</table>
<?= LinkPager::widget(['pagination' => $pagination,'nextPageLabel' => '下一页', 'prevPageLabel' => '上一页', 'options'=>['class'=>'pager pager-loose'],]) ?>