Creating a dropdown list with relationships in yii

Hi, I am new to yii structure and now I am trying to create a dropdownlist from a linked table. I have a table "News" [... many fields, categories] and "NewsCategories" [id, category_name]. In the form for creating a new entry in News, I want to create a dropedownlist in the category field, when the user can select category_name, but the category identifier should be the recorder in the new entry.

Please help me with this. Sorry for my English. I hope I explain it clearly.

This is how I created the relationship

Model News.php

public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'category'=>array(self::BELONGS_TO, 'NewsCategories', 'category'), ); } 

Model NewsCategories.php

  public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'news'=>array(self::HAS_MANY, 'News', 'id'), ); } 

And how I am trying to create a dropdownlist:

 <?php echo $form->dropDownList($model,'category',CHtml::listdata(News::model()->with('category')->findAll(),'id','category_name'),array('empty'=>'(Select a category')));?> 
+4
source share
1 answer

When specifying relationships, you do not need to specify a primary key (id), because yii can subtract the primary key from the model. You only need to indicate the other end, so your NewsCategory relationship should look like this:

 'news'=>array(self::HAS_MANY, 'News', 'category'), 

To get the data suitable for the drop-down list, use

 CHtml::listData(NewsCategories::model()->findAll(), 'id', 'category_name'); 
+4
source

Source: https://habr.com/ru/post/1500201/


All Articles