You are viewing revision #1 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.
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
// check if Tags extis
if (isset($_POST['Tags'])) {
$tagsList = explode(',', $_POST['Tags']); // get the array of tags
$currentTagsList = array(); // track to have currently selected tags used for deleted
foreach ($tagsList as $TagValue) {
// check if exist in tag table or not
$isExists = Tags::model()->find('name=:name', array(':name' => $TagValue));
if (count($isExists) > 0) {
// if exists just assign
$tag = new FeedbackTags;
$tag->feedback_id = $feedback_id;
$tag->tag_id = $isExists->id;
$tag->save();
$currentTagsList[]=$tag->tag_id; // add to array for track
} else { // if not exist add to tag table and then to tags
$tagNew = new Tags;
$tagNew->name = $TagValue;
if ($tagNew->save()) {
// now add to feedbacktags table
$tag2 = new FeedbackTags;
$tag2->feedback_id = $feedback_id;
$tag2->tag_id = $tagNew->id;
$tag2->save();
$currentTagsList[]=$tag->tag_id; // add to array for track
}
}
}
}
$previousTagsList = Feedback::getAssignedTagsIDs($feedbackModel->id); // get all exist in feedbackTags table
$deletedList=array_diff($previousTagsList, $currentTagsList); // difference
if(count($deletedList)){
foreach ($deletedList as $item){
// just delete form feedbackTags table NOT from Tags , if you want you can delete
FeedbackTags::model()->find('tag_id='.$item .' AND feedback_id='.$feedbackModel->id)->delete();
}
}
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.