首页 > 解决方案 > Yii2基本模式不调用main.php

问题描述

我在 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']);
    }
}

和类别控制器:

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; ?>

标签: phpviewyii2yii2-basic-app

解决方案


首先检查您的操作名称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'));
}

引用 Yii2基础操作Yii2 Render()


推荐阅读