Problem In Copy Data From First Model To 2Nd Model

i want to copy data after savning in one model to 2nd model

my code snippets as directed by some members but not working.




protected function afterSave() //Copy data from Client to packageassignment *** assuming your you're in the Client model 

                                                                //and Client has id,package_id,p_start_date

{

        $packageassignment= new Packageassignment();

        $packageassignment->user_id=$this->id;

        $packageassignment->package_id=$this->package_id;

        $packageassignment->package_start_date=$this->p_start_date;

        $packageassignment->save();

        return parent::afterSave();

}



plz update this code .

thanks

Hi hameedhamdani

test it by

$packageassignment->save(false); //without validation

sir not working…

Ok, lets solve the problem step by step.

  1. ensure the event afterSave() of first model called properly with

adding an echo for below fields

$this->id;

$this->package_id;

$this->p_start_date;

  1. In Model Packageassignment override the afterSave() by

public afterSave() {

echo 'hello am I am the aftersave method of Packageassignment Model :)';

parent::afterSave();

}

Let me know what happen in two above cases

Sir,i applied both cases .No Error Display… No echo…Data is saved only in client model…

Are you sure the first afterSave is insideof first model ? The aftersave alwsays called on succesed save event.

Post your code of first and second model

plz see the client controller and after this the packageassignment controller .

thanks




<?php


class ClientController extends Controller

{

	/**

	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning

	 * using two-column layout. See 'protected/views/layouts/column2.php'.

	 */

	public $layout='//layouts/column2';

	

	/**

	 * @return array action filters

	 */

	public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

			'postOnly + delete', // we only allow deletion via POST request

		);

	}


	/**

	 * Specifies the access control rules.

	 * This method is used by the 'accessControl' filter.

	 * @return array access control rules

	 */

	public function accessRules()

	{

		return array(

			array('allow',  // allow all users to perform 'index' and 'view' actions

				'actions'=>array('index','view'),

				'users'=>array('*'),

			),

			array('allow', // allow authenticated user to perform 'create' and 'update' actions

				'actions'=>array('create','update'),

				'users'=>array('*'),

			),

			array('allow', // allow admin user to perform 'admin' and 'delete' actions

				'actions'=>array('admin','delete'),

				'users'=>array('*'),

			),

			array('deny',  // deny all users

				'users'=>array('*'),

			),

		);

	}


	/**

	 * Displays a particular model.

	 * @param integer $id the ID of the model to be displayed

	 */

	public function actionView($id)

	{

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

			'model'=>$this->loadModel($id),

		));

	}

	 /*

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	 public function actionCreate()

	{

    	$model=new client;

    	// Uncomment the following line if AJAX validation is needed

    	// $this->performAjaxValidation($model);

 

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

    	{

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

			


        	if($model->save())

        	{

            	if (Yii::app()->request->isAjaxRequest)

            	{

                	echo CJSON::encode(array(

                    	'status'=>'success', 

                    	'div'=>"Client successfully added"

                    	));

                	exit;           	

            	}

            	else

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

        	}

    	}

 

    	if (Yii::app()->request->isAjaxRequest)

    	{

        	echo CJSON::encode(array(

            	'status'=>'failure', 

            	'div'=>$this->renderPartial('_form', array('model'=>$model), true)));

				

        	exit;           	

    	}

    	else

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

	}

	

	/**

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	/***

	public function actionCreate()

	{

		$model=new client;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


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

		{

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

			if($model->save())

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

		}


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

			'model'=>$model,

		));

	}

***/

	/**

	 * Updates a particular model.

	 * If update is successful, the browser will be redirected to the 'view' page.

	 * @param integer $id the ID of the model to be updated

	 **when a user updated the password field then it will be encrypted also.

	 */

	public function actionUpdate($id)

	{

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

		//$oldPassword=$model->password;//Capture the old password.

		//$model->password=""; //Make this empty. else the hashed password appears as string of dots in form field.


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


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

		/*if($model->password=="")

					$model->password=$oldPassword;

		else $model->password=md5($model->password);//customize the encrypting logic in your own way.You can put some additional salt.

		*/

		{

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

			if($model->save())

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

		}


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

			'model'=>$model,

		));

	}


	/**

	 * Deletes a particular model.

	 * If deletion is successful, the browser will be redirected to the 'admin' page.

	 * @param integer $id the ID of the model to be deleted

	 */

	public function actionDelete($id)

	{

		$this->loadModel($id)->delete();


		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

		if(!isset($_GET['ajax']))

			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

	}


	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('client');

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

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new client('search');

		$model->unsetAttributes();  // clear any default values

		if(isset($_GET['client']))

			$model->attributes=$_GET['client'];


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

			'model'=>$model,

		));

	}


	/**

	 * Returns the data model based on the primary key given in the GET variable.

	 * If the data model is not found, an HTTP exception will be raised.

	 * @param integer the ID of the model to be loaded

	 */

	public function loadModel($id)

	{

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

		if($model===null)

			throw new CHttpException(404,'The requested page does not exist.');

		return $model;

	}


	/**

	 * Performs the AJAX validation.

	 * @param CModel the model to be validated

	 */

	protected function performAjaxValidation($model)

	{

		if(isset($_POST['ajax']) && $_POST['ajax']==='client-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}

	}

/*

public function afterSave()

 {

	echo 'hello am I am the aftersave method of client Model';

	parent::afterSave();

}


}

*/

/***************Copy data from Client to packageassignment ***********************/


protected function afterSave() 


{

    	$packageassignment= new Packageassignment();

    	$packageassignment->user_id=$this->id;

    	$packageassignment->package_id=$this->package_id;

    	$packageassignment->package_start_date=$this->p_start_date;


 if(!$packageassignment->save())

{

	echo 'packageassignment save failed';

}

    	return parent::afterSave();

}

/***

	echo	$this->id;

	echo $this->package_id;

	echo $this->p_start_date;

	}

***/


	/**********************code for jquery and js files  used in pop-up of cjuidatepicker*************

	public function init(){

	//load core framework scripts once, but stop them from being loaded later

	//fixes big problem that many jui and related widgets cause

	Yii::app()->clientScript->registerCoreScript('jquery');

	Yii::app()->clientScript->registerCoreScript('jquery.ui');

}


public function renderAjax($view, $data = null,$return=false,$processOutput=true){

	//dont load jQuery framework stuff twice, it causes mucho problems!

	Yii::app()->clientscript->scriptMap['jquery.js'] = false;

	Yii::app()->clientscript->scriptMap['jquery-ui.min.js'] = false;

	Yii::app()->clientscript->scriptMap['jquery.yiigridview.js'] = false;

	Yii::app()->clientscript->scriptMap['jquery.ba-bbq.js'] = false;


	$this->renderPartial($view,$data,$return,$processOutput);

}

******************************************************************************************/


}






2nd packagecontroller.php




<?php


class PackageassignmentController extends Controller

{

	/**

	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning

	 * using two-column layout. See 'protected/views/layouts/column2.php'.

	 */

	public $layout='//layouts/column2';


	/**

	 * @return array action filters

	 */

	public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

			'postOnly + delete', // we only allow deletion via POST request

		);

	}


	/**

	 * Specifies the access control rules.

	 * This method is used by the 'accessControl' filter.

	 * @return array access control rules

	 */

	public function accessRules()

	{

		return array(

			array('allow',  // allow all users to perform 'index' and 'view' actions

				'actions'=>array('index','view'),

				'users'=>array('*'),

			),

			array('allow', // allow authenticated user to perform 'create' and 'update' actions

				'actions'=>array('create','update'),

				'users'=>array('*'),

			),

			array('allow', // allow admin user to perform 'admin' and 'delete' actions

				'actions'=>array('admin','delete'),

				'users'=>array('*'),

			),

			array('deny',  // deny all users

				'users'=>array('*'),

			),

		);

	}


	/**

	 * Displays a particular model.

	 * @param integer $id the ID of the model to be displayed

	 */

	public function actionView($id)

	{

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

			'model'=>$this->loadModel($id),

		));

	}


/*

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	 public function actionCreate()

	{

    	$model=new packageassignment;

 

    	// Uncomment the following line if AJAX validation is needed

    	// $this->performAjaxValidation($model);

 

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

    	{

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

        	if($model->save())

        	{

            	if (Yii::app()->request->isAjaxRequest)

            	{

                	echo CJSON::encode(array(

                    	'status'=>'success', 

                    	'div'=>"Package Assignment successfully added"

                    	));

                	exit;           	

            	}

            	else

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

        	}

    	}

 

    	if (Yii::app()->request->isAjaxRequest)

    	{

        	echo CJSON::encode(array(

            	'status'=>'failure', 

            	'div'=>$this->renderPartial('_form', array('model'=>$model), true)));

        	exit;           	

    	}

    	else

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

	}

	


	/**

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

/***	 

	public function actionCreate()

	{

		$model=new packageassignment;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


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

		{

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

			if($model->save())

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

		}


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

			'model'=>$model,

		));

	}

	

	***/


	/**

	 * Updates a particular model.

	 * If update is successful, the browser will be redirected to the 'view' page.

	 * @param integer $id the ID of the model to be updated

	 */

	public function actionUpdate($id)

	{

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


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


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

		{

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

			if($model->save())

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

		}


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

			'model'=>$model,

		));

	}


	/**

	 * Deletes a particular model.

	 * If deletion is successful, the browser will be redirected to the 'admin' page.

	 * @param integer $id the ID of the model to be deleted

	 */

	public function actionDelete($id)

	{

		$this->loadModel($id)->delete();


		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

		if(!isset($_GET['ajax']))

			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

	}


	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('packageassignment');

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

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new packageassignment('search');

		$model->unsetAttributes();  // clear any default values

		if(isset($_GET['packageassignment']))

			$model->attributes=$_GET['packageassignment'];


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

			'model'=>$model,

		));

	}


	/**

	 * Returns the data model based on the primary key given in the GET variable.

	 * If the data model is not found, an HTTP exception will be raised.

	 * @param integer the ID of the model to be loaded

	 */

	public function loadModel($id)

	{

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

		if($model===null)

			throw new CHttpException(404,'The requested page does not exist.');

		return $model;

	}


	/**

	 * Performs the AJAX validation.

	 * @param CModel the model to be validated

	 */

	protected function performAjaxValidation($model)

	{

		if(isset($_POST['ajax']) && $_POST['ajax']==='packageassignment-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}

	}

}




Hi hameedhamdani

The after,before (save,delete) and so on, methods MUST be members method of CActiveRecord not Controller class! Migrate all afterSave methods to appropriate models AR :)

also check

http://www.yiiframework.com/doc/blog/1.1/en/post.create

http://www.yiiframework.com/doc/api/1.1/CActiveRecord#afterSave-detail