Generate Form With From 2 Models

Hi guys! I’m new to Yii and today I couldn’t solve the following problem.

I have the following table structure

post

|-----|--------|

| id | title |

|-----|--------|

category

|-----|---------|

| id | name |

|-----|---------|

| 1 | cat1 |

|-----|---------|

| 2 | cat2 |

|-----|---------|

| 3 | cat3 |

|-----|---------|

| 4 | cat4 |

|-----|---------|

post_category (Primary key (post_id, category_id))

|----------|---------------|

| post_id | category_id |

|----------|---------------|

I want the following CRUD form for my Post table(model):

  1. The form should include textField for Post->title

  2. The form should also include checkBoxList populated from Category->id and Category->name;

  3. Submit button.

Then on submit(create) my tables should be filled like these:

Post

|-----|--------|

| id | title |

|-----|--------|

| 1 | title1 |

|-----|--------|

category (does not change)

|-----|--------|

| id | name |

|-----|--------|

| 1 | cat1 |

|-----|--------|

| 2 | cat2 |

|-----|--------|

| 3 | cat3 |

|-----|--------|

| 4 | cat4 |

|-----|--------|

post_category (assuming that I checked all checkboxes)

|----------|---------------|

| post_id | category_id |

|----------|---------------|

| 1 | 1 |

|----------|---------------|

| 1 | 2 |

|----------|---------------|

| 1 | 3 |

|----------|---------------|

| 1 | 4 |

|----------|---------------|

(Sorry , wysiwyg is not displaying my tables correctly :rolleyes:. I hope you get the idea )

I think I have to use mysql transactions to insert data into two tables. But still I dont know how to update post and change the categories it belongs to. And I dont know how to generate the form I want. Please help. Thanks

just walk through the create,update actions of the generated controllers…u will get the idea. no need of sql queries atall!!

Rajith thanks. But can you please be more specific. Do I have to pass two models to my view?

What you have to do is as

Input field for the Post title.

List of Checkbox based on your categories (check How to do it at http://www.yiiframework.com/wiki/81/list-with-multiple-checkbox/)

in the update/create action of your controller, you need to do as




$categories=$_POST['categories'];

if(!empty($categories)){

if(is_array($categories)){

 foreach($categories as $cat){

  $pc=new PostCategories;

   $pc->post_id=$model->id;

   $pc->cat_id=$cat;

   $pc->save();

}

}

}



see the render array… pass like that…