UPDATED
I have two related models i.e. Candidate and Qualifications. They have one to one relationship between them. I am using CActiveForm and want to perform CRUD operation on the relational data. I had been able to insert the data but i am having issues with the update and delete. The function is displaying the $id but that the only thing that is displayed on the page.
CandidateController
public function actionUpdate($id)
{
echo $id;// this is printing the id on page
$model = Candidate::model()->findByPk($id);
$q = Qualification::model()->findAllByAttributes(array('candidate_id' => $id));
if (isset($_POST['Candidate'], $_POST['Qualification'])) {
$model->attributes=$_POST['Candidate'];
$q->attributes=$_POST['Qualification'];
$error = false;
$transaction = Yii::app()->db->beginTransaction();
try {
if (!$model->save()) {
throw new CException(CHtml::errorSummary($model));
}
$q->candidate_id = $model->id;
if (!$q->save()) {
throw new CException(CHtml::errorSummary($q));
echo $error;
}
$transaction->commit();
} catch (Exception $e) {
$transaction->rollBack();
$error = $e->getMessage();
}
if (!$error) {
$this->redirect(array('view','id'=>$model->id));
}
}
}
public function actionView($id)
{
/*$this->render('view',array(
'model'=>$this->loadModel($id),
));*/
$model = $this->loadModel($id);
$this->render('view',array(
'Candidate'=>$model,
'Qualification'=>Qualification::model()->findAllByAttributes(array('candidate_id' => $id))
));
}
I can't understand how to make the data visible in form with edit option.
UPDATING
It seems, you only have a one-to-one relationship so if that is the case you only have to link
$q
to the specific qualification:With some tweaks i.e a loop and tabular data input the above code can work for one-to-many.
DELETING
For deletion edit
Candidate::beforeDelete()
to delete all qualifications linked to it as follows:You should wrap the call to
Candidate::delete()
in a transaction.