I've following AR two definitions
News.php (only important part)
public function rules() { return array( array('title','length','max'=>100), array('author_desc','length','max'=>20), array('title, author_desc, date, time', 'required'), array('total_comments', 'numerical', 'integerOnly'=>true), ); } /** * @return array relational rules. */ public function relations() { return array( 'author'=>array(self::BELONGS_TO, 'User', 'author_id'), 'comments'=>array(self::HAS_MANY, 'NewsComment', 'news_id'), 'category'=>array(self::HAS_MANY, 'NewsCategory', 'news_id'), 'txt'=>array(self::HAS_ONE, 'NewsTxt', 'news_id'), );
NewsTxt, only important part
public function rules() { return array( array('text', 'required'), ); }
I've generated News controller and News create view and _form.php. Some of them I've modified a little bit. Below you will find changes:
NewsController
public function actionCreate() { $news=new News; $news->txt=new NewsTxt(); if(isset($_POST['News'])&&isset($_POST['NewsTxt'])) { $news->attributes=$_POST['News']; $news->txt->attributes=$_POST['NewsTxt']; if($news->save()) { $this->redirect(array('show','id'=>$news->id)); } } $this->render('create',array('news'=>$news)); }
_form.php
<div class="simple"> <?php echo CHtml::activeLabelEx($news->txt,'text'); ?> <?php echo CHtml::activeTextArea($news->txt,'text'); ?> </div> </fieldset>
afterSave in News model
protected function afterSave() { if ($this->isNewRecord) { $this->txt->news_id=$this->id; $this->txt->save(); } }
Questions
- How can I use in this approach transactions to rollBack entries saved in News table when saving in afterSave will fails?
- Should I use another aproach to achieve my coal?
- When in blog tutorial/definitive guide will appear extended description containing transactions (current description is really minimalistic)