Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8874925
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T18:50:42+00:00 2026-06-14T18:50:42+00:00

I am a Yii Beginner and I am currently working on a Tagging system

  • 0

I am a Yii Beginner and I am currently working on a Tagging system where I have 3 tables:

  • Issue (id,content,create_d,…etc)

  • Tag (id,tag)

  • Issue_tag_map (id,tag_id_fk,issue_id_fk)

In my /Views/Issue/_form I have added a MultiComplete Extension to retrieve multiple tag ids and labels,

I have used an afterSave function in order to directly store the Issue_id and the autocompleted Tag_ids in the Issue_tag_map table, where it is a HAS_MANY relation.

Unfortunately Nothing is being returned.

I wondered if there might be a way to store the autocompleted Tag_ids in a temporary attribute and then pass it to the model’s afterSave() function.

I have been searching for a while, and this has been driving me crazy because I feel I have missed a very simple step!

Any Help or advices of any kind are deeply appreciated!

MultiComplete in Views/Issue/_form:

    <?php

     echo $form->labelEx($model, 'Tag');
     $this->widget('application.extension.MultiComplete', array(
    'model' => $model,
    'attribute' => '', //Was thinking of creating a temporary here
    'name' => 'tag_autocomplete',
    'splitter' => ',',
    'sourceUrl' => $this->createUrl('Issue/tagAutoComplete'),
    // Controller/Action path for action we created in step 4.
    // additional javascript options for the autocomplete plugin
    'options' => array(
        'minLength' => '2',
    ),
    'htmlOptions' => array(
        'style' => 'height:20px;',
    ),
));
echo $form->error($model, 'issue_comment_id_fk');
?>

AfterSave in /model/Issue:

    protected function afterSave() {
    parent::afterSave();

    $issue_id = Yii::app()->db->getLastInsertID();

    $tag; //here I would explode the attribute retrieved by the view form
    // an SQL with two placeholders ":issue_id" and ":tag_id"
    if (is_array($tag))
        foreach ($tag as $tag_id) {
            $sql = "INSERT INTO issue_tag_map (issue_id_fk, tag_id_fk)VALUES(:issue_id,:tag_id)";     

            $command = Yii::app()->db->createCommand($sql);
           // replace the placeholder ":issue_id" with the actual issue value

            $command->bindValue(":issue_id", $issue_id, PDO::PARAM_STR);
           // replace the placeholder ":tag_id" with the actual tag_id value

            $command->bindValue(":tag_id", $tag_id, PDO::PARAM_STR);
            $command->execute();
        }
}

And this is the Auto Complete sourceUrl in the Issue model for populating the tags:

    public static function tagAutoComplete($name = '') {

    $sql = 'SELECT id ,tag AS label FROM tag WHERE tag LIKE :tag';
    $name = $name . '%';
    return Yii::app()->db->createCommand($sql)->queryAll(true, array(':tag' => $name));

actionTagAutoComplete in /controllers/IssueController:

// This function will echo a JSON object 
// of this format:
// [{id:id, name: 'name'}]
function actionTagAutocomplete() {

    $term = trim($_GET['term']);
    if ($term != '') {
        $tags = issue::tagAutoComplete($term);
        echo CJSON::encode($tags);
        Yii::app()->end();
    }
}

EDIT

Widget in form:

   <div class="row" id="checks" >
    <?php
    echo $form->labelEx($model, 'company',array('title'=>'File Company Distrubution; Companies can be edited by Admins'));

    ?>
   <?php
    $this->widget('application.extension.MultiComplete', array(
        'model' => $model,
        'attribute' => 'company',
        'splitter' => ',',
        'name' => 'company_autocomplete',
        'sourceUrl' => $this->createUrl('becomEn/CompanyAutocomplete'),
        'options' => array(
            'minLength' => '1',
        ),
        'htmlOptions' => array(
            'style' => 'height:20px;',
            'size' => '45',
        ),
    ));
    echo $form->error($model, 'company');
    ?>
</div>

Update function:

    $model = $this->loadModel($id);
    .....
      if (isset($_POST['News'])) {
         $model->attributes = $_POST['News'];
        $model->companies = $this->getRecordsFromAutocompleteString($_POST['News']  
       ['company']);
    ......
     ......
      getRecordsFromAutocompleteString():
  public static cordsFromAutocompleteString($string) {
    $string = trim($string);
    $stringArray = explode(", ", $string);
    $stringArray[count($stringArray) - 1] = str_replace(",", "", $stringArray[count($stringArray) - 1]);
    $criteria = new CDbCriteria();
    $criteria->select = 'id';
    $criteria->condition = 'company =:company';
    $companies = array();
    foreach ($stringArray as $company) {
        $criteria->params = array(':company' => $company);
        $companies[] = Company::model()->find($criteria);
    }
    return $companies;
}

UPDATE
since the “value” porperty is not implemented properly in this extension I referred to extending this function to the model:

    public function afterFind() {
       //tag is the attribute used in form
      $this->tag = $this->getAllTagNames();
      parent::afterFind();
   }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T18:50:44+00:00Added an answer on June 14, 2026 at 6:50 pm

    You should have a relation between Issue and Tags defined in both Issue and Tag models ( should be a many_many relation).

    So in IssueController when you send the data to create or update the model Issue, you’ll get the related tags (in my case I get a string like ‘bug, problem, …’).
    Then you need to parse this string in your controller, get the corresponding models and assigned them to the related tags.

    Here’s a generic example:

    //In the controller's method where you add/update the record
    $issue->tags = getRecordsFromAutocompleteString($_POST['autocompleteAttribute'], 'Tag', 'tag');
    

    Here the method I’m calling:

    //parse your string ang fetch the related models
    public static function getRecordsFromAutocompleteString($string, $model, $field)
            {
                $string = trim($string);
                $stringArray = explode(", ", $string);
                $stringArray[count($stringArray) - 1] = str_replace(",", "", $stringArray[count($stringArray) - 1]);
                return CActiveRecord::model($model)->findAllByAttributes(array($field => $stringArray));
            }
    

    So now your $issue->tags is an array containing all the related Tags object.

    In your afterSave method you’ll be able to do:

    protected function afterSave() {
        parent::afterSave();
    
        //$issue_id = Yii::app()->db->getLastInsertID(); Don't need it, yii is already doing it
        foreach ($this->tags as $tag) {
            $sql = "INSERT INTO issue_tag_map (issue_id_fk, tag_id_fk)VALUES(:issue_id,:tag_id)";     
            $command = Yii::app()->db->createCommand($sql);
            $command->bindValue(":issue_id", $this->id, PDO::PARAM_INT);
            $command->bindValue(":tag_id", $tag->id, PDO::PARAM_INT);
            $command->execute();
            }
    }
    

    Now the above code is a basic solution. I encourage you to use activerecord-relation-behavior’s extension to save the related model.
    Using this extension you won’t have to define anything in the afterSave method, you’ll simply have to do:

    $issue->tags = getRecordsFromAutocompleteString($_POST['autocompleteAttribute'], 'Tag', 'tag');
    $issue->save(); // all the related models are saved by the extension, no afterSave defined!
    

    Then you can optimize the script by fetching the id along with the tag in your autocomplete and store the selected id’s in a Json array. This way you won’t have to perform the sql query getRecordsFromAutocompleteString to obtain the ids. With the extension mentioned above you’ll be able to do:

    $issue->tags = CJSON::Decode($_POST['idTags']);//will obtain array(1, 13, ...)
    $issue->save(); // all the related models are saved by the extension, the extension is handling both models and array for the relation!
    

    Edit:

    If you want to fill the autocomplete field you could define the following function:

    public static function appendModelstoString($models, $fieldName)
        {
            $list = array();
            foreach($models as $model)
            {
                $list[] = $model->$fieldName;
            }
            return implode(', ', $list);
        }
    

    You give the name of the field (in your case tag) and the list of related models and it will generate the appropriate string. Then you pass the string to the view and put it as the default value of your autocomplete field.

    Answer to your edit:

    In your controller you say that the companies of this model are the one that you added from the Autocomplete form:

    $model->companies = $this->getRecordsFromAutocompleteString($_POST['News']  
       ['company']);
    

    So if the related company is not in the form it won’t be saved as a related model.
    You have 2 solutions:

    1. Each time you put the already existing related model in you autocomplete field in the form before displaying it so they will be saved again as a related model and it won’t disapear from the related models

      $this->widget('application.extensions.multicomplete.MultiComplete', array(
                      'name' => 'people',
                      'value' => (isset($people))?$people:'',
                      'sourceUrl' => array('searchAutocompletePeople'),
      ));
      
    2. In your controller before calling the getRecordsFromAutocompleteString you add the already existing models of the model.

      $model->companies = array_merge(
          $model->companies, 
          $this->getRecordsFromAutocompleteString($_POST['News']['company'])
      );
      
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm working with Yii framework and using smarty view render. I have to working
Hi i have 3 Yii based systems, something like: sys1.domain.com sys2.domain.com sys3.domain.com now, this
I am currently extending yii-s admin extension, yiiadmin. What would be the easiest way
I have configured APC Cache for YII application but when I put a variable
I'm working on a Yii application in which in some part of it I
Yii beginner here. I am facing some problem with how to query the database
I'm fairly new to Yii and have run into a barrier with related models.
With Yii php framework, I use inheritance. In my AbstractModel, I have this method:
I have a Yii project with a main.php config file and dev.php config file
Disclaimer: Complete beginner in Yii, Some experience in php. In Yii, Is it OK

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.