Taggable Behaviour

This extension allows active record model to manage tags.

Feel free to request new features, ask questions and report bugs.



where can it be downloaded ? The extension page doesn’t provide any file !


There is a link to SVN repository. You can check files out of it.

ok, thanks samdark


Updated extension. This version is not backwards compatible to 0.6.


[*] Do not try to delete tag bindings when inserting new record.

[+] Added taggedWith() alias withTags().

[-] Removed getCountByTags(), findAllByTags(). Use taggedWith().

[+] Method chaining: $post->addTags("yii, php")->save();

[+] New syntax: $posts = Post::model()->taggedWith(array(‘php’, ‘yii’))->findAll();

[*] Added parent:: calls in event handlers.

[+] Added hasTags() and it’s alias hasTag() to check if all tags specified are attached to current model.

[+] New syntax: echo $post->tags (or by what name behaviour is attached) will print comma separated tags.

[*] getTags now returns array since implode is really easy to do yourself.

[-] Removed getTagsArray().

[*] addTags(), removeTags(), setTags() are now accept both string and array.

[+] Added addTag() as alias of addTags(), removeTag() as alias of removeTags().

[*] Some methods are now protected.

[*] Added $with to findAllByTags().

[+] getAllTags().

[+] Unit tests.

[+] createTagsAutomatically option allows to throw exception when adding nonexisting tag.


since i just started using yii I might be missing something

but it seems that the init method is never called

which means the cache will not be initialized

i use the behaviour like this in my project controller:

public function behaviors()


	return array(

		'TaggableBehaviour' => array(

			'class' => 'ext.CTaggableBehaviour.CTaggableBehaviour',

			'tagBindingTable' => 'project_tag',

			'cacheID' => 'cache',




is this a bug?



Yes, it was. Just fixed it in SVN. Thanks.

Another changes are:

  • Now you can set tagId field name for binding table.

  • Added "Using multiple tag groups" to readme.


i found another cache issue



both store the result in the cache but the value is never changed when a tag is added / removed

i think it might be useful to trigger an event when tags are updated

that way it would be easier to extend the class and make use of the caching

it would also be nice to use the cached tags to check if there is something to update in afterSave

just some thoughts…

Released 0.9:

  • Added resetAllTagsCache() and resetAllTagsWithModelsCountCache().

  • Fixed getAllTags() and getAllTagsWithModelsCount() cache issues.

  • Now tags are saved on save() only if they were changed.

  • Extension is now compatible only with Yii 1.1.

Released 1.0


[*] More PHPDoc documentation.

[*] Fixed possible cache keys overlap when using multiple tag sets with one model.

[+] Nice HTML rendered documentation included.

how should i use this extension in such a case:

I have a model. The model uses etaggable behaviour. I search the model instances and want to show results (model instances and theirs tags). If I add getTags() in afterFind() method, there will be a query to DB for each instance, which is not what I want. How should it be done?

What about using cache?

I don’t understand this ‘cache suggestion’, because I can have a plenty of models and plenty of queries.

I’m rather looking for ‘eager loading’ – I want my model instances WITH theirs tag (more sql columns in one query). Of course I could do it not using ‘taggable behaviour’, but if I already use your extension it would be nice to use it consistently.



Right now I’m busy with Yii core. Will try adding it later: http://code.google.com/p/yiiext/issues/detail?id=24

Released 1.3.


How to organize views for create/update actions with taggable model?


If i use code example below, tags field clears after validation fail of other fields.


Очень не хватает примера, как правильно реализовать представление для создания/обновления модели с Taggable Behaviour и валидацию. Дело в том, что во первых в MyModel.rules() правила валидации тегов засунуть не получается, а во вторых: если в представление для создания/обновления модели просто засунуть еще одно поле (например так)

in _form.php:

<div class="row">

        <?php echo $form->labelEx($model,'tags'); ?>

        <?php echo $form->textField($model,'tags'); ?>

        <?php echo $form->error($model,'tags'); ?>


in model:

protected function beforeSave()






            return true;



            return false;


То при неудачной валидации поле с заполненными тегами обновляется.


You can use toString() to fill tags for a model.

samdark, можно детальнее? Я это реализовал, как показано в коде выше и оно работает, теги сохраняются, но я не уверен, что это лучший путь + я не знаю, как архитектурно правильно реализовать валидацию.

Еще поле с тегами обнуляется после неудачной валидации формы, если что-нибудь другое заполнить неправильно (модель, контроллеры и представления стандартные для CRUD, сгенерированы с помощью инструментов yii).

Вручную делать преобразование массива тегов в строку для этого мне вроде-бы нигде не нужно было.


I’m using the following code


but I get

Fatal error: Call to a member function toString() on a non-object