Multiple Models within a Module

Hello all,

I have a module named Contact which stores the contact information of the employees.There are two models in this module - Contact and ContactComment. ContactComment is used to store comments posted by the user and a Contact can have muliple comments. I didn’t had any issue in inserting the comment. But when I tried to edit the comment, the application reports an error related to non-existent attribute in the primary model class.


Property "Contact.contact_id" is not defined.

Here is my model definitions:


Contact -> id, firstname, lastname, designation, email, phone, mobile, etc..

ContactComment -> id, contact_id, comment_text, created_time, modified_time, etc..



This is my actionCreate() and it works without any issues.


$model=new ContactComment;

$this->performAjaxValidation($model);

if(isset($_POST['ContactComment']))

{

   $model->attributes=$_POST['ContactComment'];

   if($model->save($_POST['ContactComment'])) {

   $this->redirect(array('comment/create','contact_id'=>$model->contact_id));

} 

$model->contact_id = $contact_id;

$this->render('create',array('model'=>$model));

This is the actionUpdate() and this is the one having the errors:


$model= $this->loadModel($id);

$this->performAjaxValidation($model);

if(isset($_POST['ContactComment']))

{

   $model->attributes=$_POST['ContactComment'];

   if($model->save()) {

      $this->redirect(array('default/view','id'=>$model->contact_id));

   }

}

$model->contact_id = $contact_id;

$this->render('update',array(

'model'=>$model,

));

Why does $this points to the primary model(Contact) instead of the secondary model(ContactComment). Am I doing something wrong?

thanks

what controller you are using to define these methods if you are in Coment controller obviously you gonna get error because you dont have a field name contact_id

Hi,

I guess that method is in your Comment controller, right? So your loadModel($id) would load the Comment with id = $id, so you’re manipulating a $model that is an instance of Contact, not ContactComment.

You could change your loadModel method to include the model as parameter (like in Giix), or just do it manually:


$model = ContactComment::model()->findByPk($id);

I believe this has nothing to do with the error. However:

  • In controllers, $this refers to the current controller.

  • The same applies to views (except inside a widget / component, where $this refers to the widget / component).

  • In models, $this refers to the current model.

See also: http://stackoverflow.com/questions/11250342/basic-yii-concept-where-is-this-defined

@bennouna

Thanks for your suggestion. It worked perfectly.