Simple Tagging Component
This is a quick and easy tagging component that allows you to handle text field, comma-separated input.
It first parses the submitted data and then checks for the existence of each tag, before deciding whether to create it or not. It expects a model called Tag in a HABTM association with the calling controller.
Save this as /app/controllers/components/tagging.php and include it in your $components array.
Usage:
This will parse the data back into the correct form for simply doing a...
(originally posted at http://ben.milleare.com/2006/08/29/tagging-in-cakephp/)
Save this as /app/controllers/components/tagging.php and include it in your $components array.
Component Class:
Download code
<?php
class TaggingComponent extends Object
{
function tagParse($tagdump) {
// first we need to split the tags up and strip whitespace at the beginning and end
// not ALL whitespace as we're allowing multiple word tags
$tempTagArray = preg_split('/,/',$tagdump);
$tagArray = array();
foreach ($tempTagArray as $t) {
$t = trim($t);
if (strlen($t)>0) {
$tagArray[] = $t;
}
}
$Tag = new Tag; // create a new Tag object
$tagInfo = array(); // create a new array to store tag id and name combo's from db
foreach ($tagArray as $t) {
if ($res = $Tag->findByName($t)) {
// tag exists already, add it to our array
$tagInfo[] = $res['Tag']['id'];
} else {
// tag doesn't exist, lets add it
$Tag->save(array('id'=>'','name'=>$t));
// now we can add this to our array
$tagInfo[] = sprintf($Tag->getLastInsertID());
}
unset($res);
}
return $tagInfo;
}
}
?>
Usage:
Controller Class:
Download code
<?php
...
$this->params[’data’][’Tag’][’Tag’] = $this->Tagging->tagParse($theTagField);
...
?>
This will parse the data back into the correct form for simply doing a...
Controller Class:
Download code
<?php
...
$this->controller->save($this->params[’data’]);
...
?>
(originally posted at http://ben.milleare.com/2006/08/29/tagging-in-cakephp/)
Comments
Comment
1 Trimming Whitespaces
PHP has a function called *trim* which should used for this. It's much faster than this regex-replace.
http://php.net/manual/en/function.trim.php
Comment
2 Thanks
Question
3 Why not a Model
Bug
4 Model access
$Tag = new Tag; // create a new Tag object
Solved that changing it to:
$Tag =& new Tag; // create a new Tag object
This is also the component best practice to access the model like said in the manual.
Question
5 Help
The tagging example in the Cake Manual seemed incomplete... I'm guessing this is based off of that somehow.
Thanks-m
Comment
6 Tag Schema
http://forge.mysql.com/wiki/TagSchema