CakePHP Tags

Tagging for content is important as it help to group the content in a specific tag or more than one category of tags. Tagging also help to reduce time for user to search for content in the same area of interest. For example, this article is published in CakePHP section where it also has been tagged under Tutorial, CakePHP. If the user interested in CakePHP posting, they can easily reach the content tagged under CakePHP by clicking at the tag. 

Creating a tags, required an additional tables to store the tags information. below is the sample of tags implement for documents table. The documents table store information regarding to the metadata of the document and the groups table use to store tags. documents_group table is a bridge entity to store the tags for document. One document are belongs to one tag or many tags. It is depend on the content creator to tag the document.


The documents model (Document.php at ...app/model) should consist Has And Belong to Many (HABTM) relation ship with the groups table. The documents and group table is join by document_groups table as shown below:

public $hasAndBelongsToMany = array(
	'Group' => array(
		'className' => 'Group',
		'joinTable' => 'document_groups',
		'foreignKey' => 'figure_id',
		'associationForeignKey' => 'group_id',
		'unique' => 'keepExisting',
		'conditions' => '',
		'fields' => '',
		'order' => '',
		'limit' => '',
		'offset' => '',
		'finderQuery' => '',
	)
);


Next, at the add new document page (add.ctp at .../app/View/Documents), simply add the input to call the tags as shown below:

<div class="form-group">
<?php echo $this->Form->input('Group', array('label'=>'Group Tags',));?>
</div>


Next, at the document controller (DocumentsController.php at .../app/Controller), load the Group model and set to find the list of available tags as shown below:

public function add() {
	$this->loadModel('Group');
	$this->set('group_id', $this->Group->find('list',array('fields'=>array('id','category'))));
		if ($this->request->is('post')) {
			$this->Document->create();
			if ($this->Document->save($this->request->data)) {
				$this->Session->setFlash(__('<i class="fas fa-check"></i> Document Saved.'), 'flash/success');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('<i class="fas fa-exclamation"></i> Error. Please check input.'), 'flash/error');
			}
		}
	$groups = $this->Document->Group->find('list');
	$this->set(compact('groups'));
}


Don't forget to check and save everything. Then refresh your add page and look at the 'Group Tags' input field. It should list the available tags. (Note: Developer need to create tag first at tags table). The output should display as shown below:


All the best and happy programming :)