Реализовал вывод категорий на сайте(в админке и в блоге), идентично по это му коду пытаюсь сделать вывод тегов ,в админ ку я добавил добавление тегов при создании статьи,а вот вывести список статей которые попадают под кликабильный тег не получается.Я копернул код вьюшки и модели вывода категорий и изменил для вывода тегов так.
например:
category.php
<h6><a href="<?= Url::toRoute(['site/category','id'=>$article->category->id])?>"> <?= $article->category->title?></a></h6>
tag.php
на
<h6><a href="<?= Url::toRoute(['site/tag,'id'=>$article->tag->id])?>"> <?= $article->tag->title?></a></h6>
Вот весь код вывода категорий
Код: Выделить всё
<?php
use yii\helpers\Url;
use yii\widgets\LinkPager;
?>
<!--main content start-->
<div class="main-content">
<div class="container">
<div class="row">
<div class="col-md-8">
<?php
/** @var TYPE_NAME $articles */
foreach($articles as $article):?>
<article class="post post-list">
<div class="row">
<div class="col-md-6">
<div class="post-thumb">
<a href="<?= Url::toRoute(['site/view','id'=>$article->id]);?>"><img src="<?= $article->getImage();?>" height="200" alt="" class="pull-left"></a>
<a href="<?= Url::toRoute(['site/view','id'=>$article->id]);?>" class="post-thumb-overlay text-center">
<div class="text-uppercase text-center">Посмотреть</div>
</a>
</div>
</div>
<div class="col-md-6">
<div class="post-content">
<header class="entry-header text-uppercase">
<h6><a href="<?= Url::toRoute(['site/category','id'=>$article->category->id])?>"> <?= $article->category->title?></a></h6>
<h1 class="entry-title"><a href="<?= Url::toRoute(['site/view','id'=>$article->id]);?>">Посмотреть</a></h1>
</header>
<div class="entry-content">
<p><?= $article->description?>
</p>
</div>
<div class="social-share">
<span class="social-share-title pull-left text-capitalize"> Автор <?= $article->author->username;?> опубликовано <?= $article->getDate();?></span>
</div>
</div>
</div>
</div>
</article>
<?php endforeach;?>
<?php
/** @var TYPE_NAME $pagination */
echo LinkPager::widget([
'pagination' => $pagination
]);
?>
</div>
<?= /** @var TYPE_NAME $popular */
/** @var TYPE_NAME $categories */
/** @var TYPE_NAME $recent */
$this->render('/partials/sidebar', [
'popular'=>$popular,
'recent'=>$recent,
'categories'=>$categories
]);?>
</div>
</div>
</div>
<!-- end main content-->
Код: Выделить всё
<?php
namespace app\models;
use Yii;
use yii\data\Pagination;
/**
* This is the model class for table "{{%category}}".
*
* @property int $id
* @property string $title
*/
class Category extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%category}}';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['title'], 'string', 'max' => 255],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'title' => Yii::t('app', 'Title'),
];
}
public function getArticles()
{
return $this->hasMany(Article::className(), ['category_id' => 'id']);
}
public function getArticlesCount()
{
return $this->getArticles()->count();
}
public static function getAll()
{
return Category::find()->all();
}
public static function getArticlesByCategory($id)
{
// build a DB query to get all articles
$query = Article::find()->where(['category_id'=>$id]);
// get the total number of articles (but do not fetch the article data yet)
$count = $query->count();
// create a pagination object with the total count
$pagination = new Pagination(['totalCount' => $count, 'pageSize'=>6]);
// limit the query using the pagination and retrieve the articles
$articles = $query->offset($pagination->offset)
->limit($pagination->limit)
->all();
$data['articles'] = $articles;
$data['pagination'] = $pagination;
return $data;
}
}
Код: Выделить всё
<?php
namespace app\controllers;
use app\models\Article;
use app\models\Category;
use app\models\CommentForm;
use dektrium\user\models\LoginForm;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\web\NotFoundHttpException;
use app\models\Tag;
class SiteController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'backColor'=>0xFFFFFF, //цвет фона капчи
'testLimit'=>2, //сколько раз капча не меняется
'foreColor'=>0xE16020, //цвет символов
'minLength' => 4,
'maxLength' => 8,
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionIndex()
{
$data = Article::getAll(2);
$popular = Article::getPopular();
$recent = Article::getRecent();
$categories = Category::getAll();
$tag = Tag::getAll();
return $this->render('index',[
'articles'=>$data['articles'],
'pagination'=>$data['pagination'],
'popular'=>$popular,
'recent'=>$recent,
'categories'=>$categories,
'tag'=>$tag
]);
}
public function actionView($id)
{
if (!$article = Article::findOne($id)) {
throw new NotFoundHttpException('Article not found');
}
$article = Article::findOne($id);
$popular = Article::getPopular();
$recent = Article::getRecent();
$categories = Category::getAll();
$tag = Tag::getAll();
$comments = $article->getArticleComments();
$commentForm = new CommentForm();
$article->viewedCounter();
return $this->render('single', [
'article' => $article,
'popular' => $popular,
'recent' => $recent,
'categories' => $categories,
'tag' => $tag,
'comments' => $comments,
'commentForm' => $commentForm
]);
}
public function actionComment($id)
{
$model = new CommentForm();
if(Yii::$app->request->isPost)
{
$model->load(Yii::$app->request->post());
if($model->saveComment($id))
{
Yii::$app->getSession()->setFlash('comment', 'Your comment will be added soon!');
return $this->redirect(['site/view','id'=>$id]);
}
}
}
public function actionCategory($id)
{
$data = Category::getArticlesByCategory($id);
$popular = Article::getPopular();
$recent = Article::getRecent();
$categories = Category::getAll();
$tag = Tag::getAll();
return $this->render('category',[
'articles'=>$data['articles'],
'pagination'=>$data['pagination'],
'popular'=>$popular,
'recent'=>$recent,
'categories'=>$categories,
'tag'=>$tag
]);
}
public function actionTag($id)
{
$data = Category::getArticlesByCategory($id);
$popular = Article::getPopular();
$recent = Article::getRecent();
$categories = Category::getAll();
$tag = Tag::getAll();
return $this->render('category',[
'articles'=>$data['articles'],
'pagination'=>$data['pagination'],
'popular'=>$popular,
'recent'=>$recent,
'categories'=>$categories,
'tag'=>$tag
]);
}
}
Что я не правильно делаю ???