1. Go to this page and download the library: Download sjaakp/yii2-taggable library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
sjaakp / yii2-taggable example snippets
namespace app\models;
use sjaakp\taggable\TaggableBehavior;
class Article extends ActiveRecord {
public function behaviors()
{
return [
'taggable' => [
'class' => TaggableBehavior::class,
'junctionTable' => 'article_tag',
'tagClass' => Tag::class,
]
];
}
// ...
}
### TagBehavior ###
Class `Tag` behaves as a *tag*, and looks something like this:
namespace app\models;
use sjaakp\taggable\TagBehavior;
class Tag extends ActiveRecord {
public function behaviors()
{
return [
'tag' => [
'class' => TagBehavior::class,
'junctionTable' => 'article_tag',
'modelClass' => Article::class,
]
];
}
// ...
}
After attaching **TagBehavior** the class `Tag`. gains a few new properties and methods.
A link to the Tag view can be obtained by:
$link = $tag->link;
`models` gets all Articles tagged by `$tag`:
$taggedArticles = $tag->models;
If you'd rather have an [ActiveDataProvider](https://www.yiiframework.com/doc/api/2.0/yii-data-activedataprovider)
to access them, use:
$providerOfTaggedArticles = $tag->getModels();
The count of tagged Articles:
$countTaggedArticles = $tag->modelCount;
### Article view ###
In the `Article` view we can now display the tags like so:
// ...
/**
* @var yii\web\View $this
* @var ap\models\Article $model
*/
namespace app\controllers;
use yii\web\Controller;
use app\models\Tag;
use sjaakp\taggable\TagSuggestAction;
class TagController extends Controller {
public function actions() {
return [
'suggest' => [
'class' => TagSuggestAction::class,
'tagClass' => Tag::class,
],
];
}
// ...
}
### TagEditor ###
In the `Article`'s update and create views we can now use the **TagEditor** widget. Add something like this to `views\article\_form.php`:
use yii\helpers\Url;
use sjaakp\taggable\TagEditor;
/**
* @var yii\web\View $this
* @var app\models\Article $model
* @var yii\widgets\ActiveForm $form
*/
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.