Advanced usage: generate links on tags
antonkomarev opened this issue · comments
Here is how I'm using tags without SluggableBehavior.
In application config:
'components' => [
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules'=> [
['pattern'=>'tag/<tag>', 'route'=>'tag/view'],
]
],
]
In view file:
<?php foreach ($model->getTagNames(true) as $tag) : ?>
<?= Html::a($tag, ['/tag/view', 'tag' => $tag]) ?>
<?php endforeach ?>
If we have a tag tag with whitespace
we will have a generated link:
/tag/tag+with+whitespace
This link will call TagController:actionView()
method and bypass tag
parameter in Yii::$app->request->queryParams
array.
What is the best way to get tags slugs in a view to bypass them in URL?
@a-komarev As i remember we discuss that already. The best way to do that:
<?php foreach ($model->tags as $tag) : ?>
<?= Html::a($tag, ['/tag/view', 'tag' => $tag->slug]) ?>
<?php endforeach ?>
@creocoder Sorry, looks like I forgot a details.
The correct example will be:
<?php foreach ($model->tags as $tag) : ?>
<?= Html::a($tag->name, ['/tag/view', 'tag' => $tag->slug]) ?>
<?php endforeach ?>
Because $tag
couldn't be passed in Html::a()
function, it will be an object in this case.
Just realized that all search functions of TaggableQueryBehavior
wouldn't be useful in that example. Because all searches are performed by name
attribute and not working with slug.
Thats solving in Model which using TaggableBehavior
by assigning tagNameAttribute
as slug
:
[
'class' => TaggableBehavior::className(),
'tagNameAttribute' => 'slug',
],
Thanks, Alexander, for flexibility :}
My bad. Another problem rising. If you are setting tagNameAttribute
as slug
search will work, but adding new tags will write them in slug
field too :( Do we need to extend TaggableQueryBehavior
and add there find by slug functions?
Here is a quick solution for SluggableBehavior
support: #13