我在Yii2框架上使用基本模式。我创建两个控制器-SiteController和CategoryController。我有两个视图很少的文件夹-网站(索引和关于)和类别(类别和搜索)。 当我通过SiteController渲染视图时,一切正常,但是当我通过CategoryController actionSearch渲染视图时-不要调用main.php并且在视图中不显示任何html,但是如果我调用die-结果就在那里。 这是一个代码: 型号:
namespace app\models;
use yii\db\ActiveRecord;
class Categories extends ActiveRecord
{
public static function tableName()
{
return 'categories';
}
public function getProducts(){
return $this->hasMany(Products::className(), ['category_id' => 'id']);
}
}
和CategoryController:
public function actionSrch() {
$cat = Categories::findOne(1);
$q = Yii::$app->request->get('q');
if(isset($q) and $q!=''){
$query = Products::find()->where(['like', 'title', $q]);
// pagination
$pages = new Pagination([
'totalCount' => $query->count(),
'pageSize' => 4,
'forcePageParam' => false,
'pageSizeParam' => false ]);
$products = $query->offset($pages->offset)->limit($pages->limit)->all();
}else{
$products = Products::find()->where('title<>:title', [':title'=>''])->all();
}
$this->render('search', compact('products','pages', 'q', 'cat'));
}
和“搜索”表单:
<div class="col-sm-3">
<div class="search_box pull-right">
<form action="<?= \yii\helpers\Url::to(['categories/search']) ?>" method="get">
<input type="text" placeholder="Search" name="aaa">
</form>
</div>
</div>
和search.php中的视图
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\LinkPager;
<ul class="catalog category-products">
<?= \app\components\MenuWidget::Widget(['tpl' => 'menu']) ?>
</ul>
<div class="col-sm-9 padding-right">
<div class="features_items"><!--features_items-->
<?php if(!empty($products)): ?>
<?php $i = 0; foreach($products as $prd): ?>
<h2><?= $prd->price ?></h2>
<?php endif; ?>
<?php endforeach; ?>
<?php else :?>
<div class="alert alert-danger">Do not have products!!!</div>
<?php endif; ?>
答案 0 :(得分:1)
首先破解您的动作名称actionSrch
或actionSearch
。
并在渲染文件之前添加return
,如下所示。
public function actionSrch() {
$cat = Categories::findOne(1);
$q = Yii::$app->request->get('q');
if(isset($q) and $q!=''){
$query = Products::find()->where(['like', 'title', $q]);
// pagination
$pages = new Pagination([
'totalCount' => $query->count(),
'pageSize' => 4,
'forcePageParam' => false,
'pageSizeParam' => false
]);
$products = $query->offset($pages->offset)->limit($pages->limit)->all();
}else{
$products = Products::find()->where('title<>:title', [':title'=>''])->all();
}
return $this->render('search', compact('products','pages', 'q', 'cat'));
}