Sometime its very important to perform many actions/operation with limited time frame for friendly use, select2 provides a lot of such functionality , I just extend it tags functionality to provide a quick use for developer to save time, as I spent much time on it.
I this tutorial we will add , delete , list all all and probably update tags. I my case ,I have three tables Feedback, Tag, Feedbacktags. For feedbacktags and tags are important .
Feedback(id,……..) Feedbacktags(id, feedback_id, tag_id), Tag(id, name,….)
- Load all tags to text field
echo CHtml::textField('Tags','',array('id'=>'tags','class'=>'span5','cols'=>'45','rows'=>'3')); $this->widget('ext.select2.ESelect2',array( 'selector'=>'#tags', 'options'=>array( 'tags'=> Feedback::getTags(), // you tags list ), 'htmlOptions' => array( 'multiple' => 'multiple', ), ));
- Define method in Feedback model to have a tags assigned to it (if so)
public function getAssignedTagsIDs($id) { // for deleting in tag section $models= FeedbackTags::model()->findAll('feedback_id='.$id); $result = array(); foreach ($models AS $employee) { $result[] = $employee->tag_id; } return $result; }
- In your controller where your adding tags like in update
if (isset($_POST['Tags'])) { // Tags exits $tagsList = explode(',', $_POST['Tags']); $currentTagsList = array(); // current tags $previousTagsList2 = Feedback::getAssignedTagsIDs($feedbackModel->id); foreach ($tagsList as $TagValue) { // added to list $isExists = Tags::model()->find('name=:name', array(':name' => $TagValue)); if (count($isExists) > 0) { // update currentTagList $currentTagsList[]=$isExists->id; } else { // add new and update currentTagList $tagNew = new Tags; $tagNew->name = $TagValue; if ($tagNew->save()) { $currentTagsList[]=$tagNew->id; } } } $deletedList=array_diff($previousTagsList2, $currentTagsList); // deleted list $addedList=array_diff($currentTagsList, $previousTagsList2); // added list foreach ($addedList as $add) { // added new items $tag2 = new FeedbackTags; $tag2->feedback_id = $feedback_id; $tag2->tag_id = $add; $tag2->save(); } foreach ($deletedList as $deleted) { // deleted list if exits FeedbackTags::model()->find('tag_id='.$deleted .' AND feedback_id='.$feedbackModel->id)->delete(); } }