Using Yii ActiveRecord to Assign from a List of Values

Often times you'll have a database table containing a list of values, and you want to assign one of those values to another entity. Imagine you're assigning an author to a book, or a currency type to a sale amount, or a country preference to a user. In all these cases you have one table/class representing a list of values, and one table/class that stores, among other things, a reference to a value/instance in the first table/class.

Luckily, Yii makes it easy for you do implement this.

For this example we're going to focus on books and authors, because everyone still reads books, right?

Let's say you have an Author table, which stores an auto-incrementing id ("Id") and the author's name ("Name"). Then, let's say you have a Book table, which stores a foreign key reference to the Author table ("AuthorId").

Assuming you've created the tables (hopefully using migration scripts), models (possibly using gii), and controllers & views (also possibly using gii), you could then put the following code in your Book create/edit form, allowing the user to select the author:

<?php echo $form->labelEx($model,'AuthorId'); ?>
<?php echo $form->dropDownList($model,'AuthorId', Author::model()->getSelectList()); ?>
<?php echo $form->error($model,'AuthorId'); ?>

And put this function in your Author model:

public function getSelectList()
{
  return CHtml::listData($this->findAll(new CDbCriteria(array('order'=>'Name ASC'))),'Id','Name');
}

Make sure you add a rule in the Book model to (a) ensure validity and (b) make this field ok for massive assignment:

array('AuthorId', 'numerical', 'integerOnly'=>true),

You'll probably want to add a relation as well for easy access to the country name, as such:

'author' => array(self::BELONGS_TO, 'Author', 'AuthorId'),

Here are some further thoughts on this topic
- If you find you are making selections like this from lots of different models, you might want to consider adding this getSelectList to your base ActiveRecord class.
- If you prefer to use and auto-complete instead of a drop-down, you can implement Yii's CJuiAutoComplete in your form.

Category:
Tags:

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.