yii2-taggable A modern taggable behavior for the Yii framework.

  1. Installation
  2. Configuring
  3. Usage

Author Source Code Build Status Code Coverage Code Quality

A modern taggable behavior for the Yii framework.

Installation

The preferred way to install this extension is through composer.

Either run

$ php composer.phar require creocoder/yii2-taggable:dev-master

or add

"creocoder/yii2-taggable": "dev-master"

to the require section of your composer.json file.

Configuring

Configure model as follows

use creocoder\taggable\TaggableBehavior;

/**
 * ...
 * @property string $tagNames
 */
class Post extends \yii\db\ActiveRecord
{
    public function behaviors()
    {
        return [
            TaggableBehavior::className(),
        ];
    }

    public function rules()
    {
        return [
            //...
            ['tagNames', 'safe'],
        ];
    }

    public function transactions()
    {
        return [
            self::SCENARIO_DEFAULT => self::OP_ALL,
        ];
    }

    public static function find()
    {
        return new PostQuery(get_called_class());
    }

    public function getTags()
    {
        return $this->hasMany(Tag::className(), ['id' => 'tag_id'])
            ->viaTable('post_tag_assn', ['post_id' => 'id']);
    }
}

Configure query class as follows

use creocoder\taggable\TaggableQueryBehavior;

class PostQuery extends \yii\db\ActiveQuery
{
    public function behaviors()
    {
        return [
            TaggableQueryBehavior::className(),
        ];
    }
}

Usage

Setting tags to the entity

To set tags to the entity

$post = new Post();

// through string
$post->tagNames = 'foo, bar, baz';

// through array
$post->tagNames = ['foo', 'bar', 'baz'];
Adding tags to the entity

To add tags to the entity

$post = Post::findOne(1);

// through string
$post->addTagNames('bar, baz');

// through array
$post->addTagNames(['bar', 'baz']);
Remove tags from the entity

To remove tags from the entity

$post = Post::findOne(1);

// through string
$post->removeTagNames('bar, baz');

// through array
$post->removeTagNames(['bar', 'baz']);
Getting tags from the entity

To get tags from the entity

$posts = Post::find()->with('tags')->all();
foreach ($posts as $post) {
    echo $post->tagNames;
}
Search entities by any tags

To search entities by any tags

// through string
$posts = Post::find()->anyTagNames('foo, bar')->all();

// through array
$posts = Post::find()->anyTagNames(['foo', 'bar'])->all();
Search entities by all tags

To search entities by all tags

// through string
$posts = Post::find()->allTagNames('foo, bar')->all();

// through array
$posts = Post::find()->allTagNames(['foo', 'bar'])->all();
1 0
6 followers
0 downloads
Yii Version: 2.0
License: BSD-2-Clause
Category: Database
Developed by: creocoder
Created on: Jan 17, 2015
Last updated: 3 years ago

Related Extensions