I'm trying to build a creation form in yii for items that needs tags associated with said items. For the sake of the question I have three tables set up to handle this. The tables: items, tags, (which both have a unique ID and name) and item_tag_relation (which holds 2 IDs) have been created, as well as the necessary models, controllers, and views.
So far, all of this is working as it should. I can go to the item/create, tag/create, and itemTagRelation/create and create each piece individually if need be. However, I'd like all three to fall under a single page. On this page I'd like to be able to input a variable number of tags into a text field separated by spaces and have the form save the tags and their relations at the same time that it saves the item. Much like the stackoverflow question creation page, now that I look at it. To this end I've gotten this javascript box MagicSuggest semi-working.
The problem is that it I can't get the tags to load from or save to the database. I know I can use the ItemController to pass in multiple models to the view, but how do I go about loading and saving a variable amount? Is there some kind of yii standard way to build and save a bunch of models all at once?
Fir your scenario, you will need to make use of the ability to extend Yii models.
You did not post any code. However, I am assuming you have a single model that is being used as a primary model for the controller. Assume the tags are linked to a book. You can extend the book model to create a field that will have no representation in the db, but is used in the form.
class Book extends CActiveRecord
{
/* Used in the form only */
public $fldBookTags;
public function rules()
{
array('title', 'required'), // title is a db field
array('fldBookTags', 'length', 'max'=>255),, // Not a db field
}
}
You can then use the field attribute 'fldBookTags' in your form like a normal variable.
Now, when the book is being saved. You want to save the tags. This should only be done after the book has saved successfully. You can do this by overwriting the afterSave() method that is part of the Books model class.
class Book extends CActiveRecord
{
/* Used in the form only */
public $fldBookTags;
public function rules() { ... }
public function afterSave() { ... }
}
The afterSave() method will contain all your required function to store the tags. Notice that $this will contain the book attributes, including the primary key of the book you just saved.
public function afterSave() {
// Split the tags into its individual values
$allTags = split(" ", $this->fldBookTags);
foreach ($allTags as $itemTag) {
$tagModel = new Tag;
$tagModel->tag_name = $itemTag;
$tagModel->book_id = $this->book_id;
}
}