Yii2 基本模式不调用 main.php



我在 Yii2 框架上使用基本模式。我创建了两个控制器 - 站点控制器和类别控制器。我有两个视图很少的文件夹 - 站点(索引和关于(和类别(类别和搜索(。 当我通过 SiteController 渲染视图时,一切都可以,但是当我通过 CategoryController actionSearch 渲染视图时 - 不要调用 main.php 并且不要在视图中显示任何 html,但如果我调用 die - 结果就在那里。 这是一个代码: 型:

namespace appmodels;
use yiidbActiveRecord;
class Categories extends ActiveRecord
{
public static function tableName()
{
return 'categories';
}
public function getProducts(){
return $this->hasMany(Products::className(), ['category_id' => 'id']);
}
}

和类别控制器:

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="<?= yiihelpersUrl::to(['categories/search']) ?>" method="get">
<input type="text" placeholder="Search" name="aaa">
</form>
</div>
</div>

以及搜索中的视图.php

use yiihelpersHtml;
use yiihelpersUrl;
use yiiwidgetsLinkPager;
<ul class="catalog category-products">
<?= appcomponentsMenuWidget::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; ?>

首先将您的操作名称actionSrchactionSearch.

并在渲染文件之前添加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'));
}

Refere Yii2 base actions and Yii2 render((

最新更新