I am working on a project. I want to save 2 models in a same form. I've tried like this: actionCreate in QController.php
public function actionCreate()
{
$model=new Question;
$test=new Answer;
if(isset($_POST['Question']) && ($_POST['Answer']))
{
$model->attributes=$_POST['Question'];
$model->question=CUploadedFile::getInstance($model,'question');
$test->attributes=$_POST['Answer'];
$valid=$model->validate();
$valid=$test->validate() && $valid;
if($valid){
$model->save(false);
$test->save(false);
$model->question->saveAs(Yii::app()->basePath . '/../images/questions/' . $model->question.'');
$this->redirect(array('view','id'=>$model->id_question));
}
}
$this->render('create',array(
'model'=>$model,
'test'=>$test,
));
}
Then, in my Q/_form.php
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'question-form',
'enableAjaxValidation'=>false,
)); ?>
<?php $answerModel = new Answer; ?>
<p class="help-block">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model, $answerModel); ?>
<?php echo $form->fileFieldRow($model,'question',array('class'=>'span5','maxlength'=>50)); ?>
<?php echo $form->textFieldRow($answerModel,'optionA',array('class'=>'span5','maxlength'=>100)); ?>
//rest of codes
<?php $this->endWidget(); ?>
I've tried this but still not save the data. How can I do to fix it? Thanks for your answer
You should validate first and then save data:
$model->attributes=$_POST['Question'];
$test->attributes=$_POST['Answer'];
$valid = $model->validate();
$valid = $location->validate() && $valid;
if ($valid) {
// use false parameter to disable validation
$model->save(false);
$test->save(false);
// redirect
}
And with transactions:
$model->attributes=$_POST['Question'];
$test->attributes=$_POST['Answer'];
$valid = $model->validate();
$valid = $location->validate() && $valid;
if ($valid) {
$dbTransaction = Yii::app()->db->beginTransaction();
try {
// use false parameter to disable validation
$model->save(false);
$test->save(false);
$dbTransaction->commit();
// redirect here
} catch (Exception $e) {
$dbTransaction->rollBack();
// save/process error
}
}