Insertion Into Two Tables At One Time

I am new in Yii, currently working on a project.

in which there are two tables…

  1. kash_users(kash_userID,kash_firstName,etc.)

  2. kash_user_login(kash_user_login_id, user_password,user_email,etc…)

I created two models for both tables, and a single controller, the problem is data is inserting into kash_users table but not in kash_user_login table, also email and password validation problem is also there, plz help me…

My models are :

model/Users.php(for kash_users table)

<?php

class Users extends CActiveRecord

{

public &#036;PasswordConfirm;


public function tableName()


{


	return 'kash_users';





}





/**


 * @return array validation rules for model attributes.


 */


 public function rules()


{


	// NOTE: you should only define rules for those attributes that


	// will receive user inputs.


	return array(


		array('kash_firstName, kash_lastName, kash_country', 'required'),


		


		array('kash_firstName', 'unique'),


		


		//array('profile', 'safe'),


		// The following rule is used by search().


		// @todo Please remove those attributes that should not be searched.


		


	);


}





/**


 * @return array relational rules.


 */


public function relations()


{


	// NOTE: you may need to adjust the relation name and the related


	// class name for the relations automatically generated below.


	return array(


	);


}





/**


 * @return array customized attribute labels (name=&gt;label)


 */


public function attributeLabels()


{


	return array(


		'kash_userId' =&gt; 'Kash User',


		'kash_user_login_id' =&gt; 'Kash User Login',


		'kash_firstName' =&gt; 'Kash First Name',


		'kash_lastName' =&gt; 'Kash Last Name',


		//'kash_address' =&gt; 'Kash Address',


		'kash_country' =&gt; 'Kash Country',


		//'kash_pincode' =&gt; 'Kash Pincode',


		//'kash_phone' =&gt; 'Kash Phone',


		//'kash_user_denomination' =&gt; 'Kash User Denomination',


		//'kash_createDate' =&gt; 'Kash Create Date',


		//'kash_updateDate' =&gt; 'Kash Update Date',


	);


}





/**


 * Retrieves a list of models based on the current search/filter conditions.


 *


 * Typical usecase:


 * - Initialize the model fields with values from filter form.


 * - Execute this method to get CActiveDataProvider instance which will filter


 * models according to data in model fields.


 * - Pass data provider to CGridView, CListView or any similar widget.


 *


 * @return CActiveDataProvider the data provider that can return the models


 * based on the search/filter conditions.


 */


public function search()


{


	// @todo Please modify the following code to remove attributes that should not be searched.





	&#036;criteria=new CDbCriteria;





	&#036;criteria-&gt;compare('kash_userId',&#036;this-&gt;kash_userId);


	&#036;criteria-&gt;compare('kash_user_login_id',&#036;this-&gt;kash_user_login_id);


	&#036;criteria-&gt;compare('kash_firstName',&#036;this-&gt;kash_firstName,true);


	&#036;criteria-&gt;compare('kash_lastName',&#036;this-&gt;kash_lastName,true);


	&#036;criteria-&gt;compare('kash_address',&#036;this-&gt;kash_address,true);


	&#036;criteria-&gt;compare('kash_country',&#036;this-&gt;kash_country);


	&#036;criteria-&gt;compare('kash_pincode',&#036;this-&gt;kash_pincode,true);


	&#036;criteria-&gt;compare('kash_phone',&#036;this-&gt;kash_phone,true);


	&#036;criteria-&gt;compare('kash_user_denomination',&#036;this-&gt;kash_user_denomination,true);


	&#036;criteria-&gt;compare('kash_createDate',&#036;this-&gt;kash_createDate,true);


	&#036;criteria-&gt;compare('kash_updateDate',&#036;this-&gt;kash_updateDate,true);





	return new CActiveDataProvider(&#036;this, array(


		'criteria'=&gt;&#036;criteria,


	));


}





/**


 * Returns the static model of the specified AR class.


 * Please note that you should have this exact method in all your CActiveRecord descendants&#33;


 * @param string &#036;className active record class name.


 * @return Users the static model class


 */


public static function model(&#036;className=__CLASS__)


{


	return parent::model(&#036;className);


}

}

mode/UserLogin.php (for kash_user_login table)

<?php

class UserLogin extends CActiveRecord

{

//public &#036;password_repeat;


public &#036;PasswordConfirm;


/**


 * @return string the associated database table name


 */


public function tableName()


{


	return 'kash_user_login';





}





public function validatePassword(&#036;user_password)


{


	return CPasswordHelper::verifyPassword(&#036;user_password,&#036;this-&gt;user_password);


}





public function hashPassword(&#036;password)


{


	return CPasswordHelper::hashPassword(&#036;password);


}


/**


 * @return string the associated database table name


 */








/**


 * @return array validation rules for model attributes.


 */


public function rules()


{


	// NOTE: you should only define rules for those attributes that


	// will receive user inputs.


	return array(


		array('user_email, user_password', 'required'),


		array('user_email', 'unique'),


		//array('user_email','preg_match()')


		array('kash_usertype_id', 'numerical', 'integerOnly'=&gt;true),


		array('user_email, user_password, kash_user_balance', 'length', 'max'=&gt;255),


		array('user_password', 'compare'),


		array('PasswordConfirm', 'safe'),


		array('kash_userStatus', 'length', 'max'=&gt;1),


		


		


		// The following rule is used by search().


		// @todo Please remove those attributes that should not be searched.


		array('kash_user_login_id, user_email, user_password, kash_usertype_id, kash_user_balance, kash_userStatus, date_created, date_updated', 'safe', 'on'=&gt;'search'),


	);


}





/**


 * @return array relational rules.


 */


public function relations()


{


	// NOTE: you may need to adjust the relation name and the related


	// class name for the relations automatically generated below.


	return array(


	);


}





/**


 * @return array customized attribute labels (name=&gt;label)


 */


public function attributeLabels()


{


	return array(


		'kash_user_login_id' =&gt; 'Kash User Login',


		'user_email' =&gt; 'User Email',


		'user_password' =&gt; 'User Password',


		'kash_usertype_id' =&gt; 'Kash Usertype',


		'kash_user_balance' =&gt; 'Kash User Balance',


		'kash_userStatus' =&gt; 'Kash User Status',


		'date_created' =&gt; 'Date Created',


		'date_updated' =&gt; 'Date Updated',


	);


}





/**


 * Retrieves a list of models based on the current search/filter conditions.


 *


 * Typical usecase:


 * - Initialize the model fields with values from filter form.


 * - Execute this method to get CActiveDataProvider instance which will filter


 * models according to data in model fields.


 * - Pass data provider to CGridView, CListView or any similar widget.


 *


 * @return CActiveDataProvider the data provider that can return the models


 * based on the search/filter conditions.


 */


public function search()


{


	// @todo Please modify the following code to remove attributes that should not be searched.





	&#036;criteria=new CDbCriteria;





	&#036;criteria-&gt;compare('kash_user_login_id',&#036;this-&gt;kash_user_login_id);


	&#036;criteria-&gt;compare('user_email',&#036;this-&gt;user_email,true);


	&#036;criteria-&gt;compare('user_password',&#036;this-&gt;user_password,true);


	&#036;criteria-&gt;compare('kash_usertype_id',&#036;this-&gt;kash_usertype_id);


	&#036;criteria-&gt;compare('kash_user_balance',&#036;this-&gt;kash_user_balance,true);


	&#036;criteria-&gt;compare('kash_userStatus',&#036;this-&gt;kash_userStatus,true);


	&#036;criteria-&gt;compare('date_created',&#036;this-&gt;date_created,true);


	&#036;criteria-&gt;compare('date_updated',&#036;this-&gt;date_updated,true);





	return new CActiveDataProvider(&#036;this, array(


		'criteria'=&gt;&#036;criteria,


	));


}





/**


 * Returns the static model of the specified AR class.


 * Please note that you should have this exact method in all your CActiveRecord descendants&#33;


 * @param string &#036;className active record class name.


 * @return UserLogin the static model class


 */


public static function model(&#036;className=__CLASS__)


{


	return parent::model(&#036;className);


}

}

my contrllers file is :

controller/ UsersContrller.php(for Users Model)

<?php

class UsersController extends Controller

{

/*public function actionIndex()


{


	&#036;this-&gt;render('index');


}

*/

//public &#036;layout='//layouts/column2';


// Uncomment the following methods and override them if needed





public function filters()


{


	return array(


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


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


	);


}


public function accessRules()


{


	return array(


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


			'actions'=&gt;array('index','view','create'),


			'users'=&gt;array('*'),


		),


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


			'actions'=&gt;array('create','update'),


			'users'=&gt;array('@'),


		),


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


			'actions'=&gt;array('admin','delete'),


			'users'=&gt;array('admin'),


		),


		array('deny',  // deny all users


			'users'=&gt;array('*'),


		),


	);


}





public function actions()


{


	// return external action classes, e.g.:


	return array(


		'action1'=&gt;'path.to.ActionClass',


		'action2'=&gt;array(


			'class'=&gt;'path.to.AnotherActionClass',


			'propertyName'=&gt;'propertyValue',


		),


	);


}


public function actionView(&#036;kash_userId)


{


	&#036;this-&gt;render('view',array(


		'model'=&gt;&#036;this-&gt;loadModel(&#036;id),


	));


}


public function actionCreate()


{


		&#036;model1 = new Countrylist;


		if(isset(&#036;_POST['Countrylist']))


	{


		&#036;model-&gt;attributes=&#036;_POST['Countrylist'];


		if(&#036;model-&gt;save())


		{


			


			&#036;this-&gt;redirect(array('view','id'=&gt;&#036;model-&gt;id));


	


			}


	}


	


	&#036;model=new Users;


	&#036;model_login = new UserLogin;


	// Uncomment the following line if AJAX validation is needed


	//&#036;this-&gt;performAjaxValidation(&#036;model_login);


	


	


	if(isset(&#036;_POST['Users']) &amp;&amp; isset(&#036;_POST['UserLogin']))


	{


		&#036;model-&gt;attributes=&#036;_POST['Users'];


		if(&#036;model-&gt;save())


		{


			


			&#036;this-&gt;redirect(array('view','id'=&gt;&#036;model-&gt;kash_userId));


			&#036;this-&gt;redirect(array('view','id' =&gt; &#036;model_login-&gt;kash_user_login_id));


		}


	


	&#036;valid=&#036;model-&gt;validate();


    &#036;valid=&#036;model_login-&gt;validate();





    if(&#036;valid)


    {


        // use false parameter to disable validation


        &#036;model-&gt;save(false);


        &#036;model_login-&gt;save();


        // ...redirect to another page


    }


	


	


	}

/*

if(isset($_POST)){

if(isset($_POST[‘Users’])) {

$model->attributes=$_POST[‘Users’];

$model->save();

}

if(isset($_POST[‘UserLogin’])){

$model_login->attributes=$_POST[‘UserLogin’];

$model_login->save();

}

//Redirect to your target page

//$this->redirect(’/’);

}

*/

	&#036;this-&gt;render('create',array(


		'model'=&gt;&#036;model, 


		'model_login'=&gt;&#036;model_login,


	));


}

}

views\users\_form.php file :

<?php

/* @var $this UsersController */

/* @var $model Users */

/* @var $form CActiveForm */

?>

<div class="form">

<?php $form=$this->beginWidget(‘CActiveForm’, array(

'id'=&gt;'users-form',


// Please note: When you enable ajax validation, make sure the corresponding


// controller action is handling ajax validation correctly.


// There is a call to performAjaxValidation() commented in generated controller code.


// See class documentation of CActiveForm for details on this.


'enableAjaxValidation'=&gt;true,

)); ?>

&lt;p class=&quot;note&quot;&gt;Fields with &lt;span class=&quot;required&quot;&gt;*&lt;/span&gt; are required.&lt;/p&gt;





&lt;?php echo &#036;form-&gt;errorSummary(&#036;model); ?&gt;





&lt;div class=&quot;row&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model_login,'Email'); ?&gt;


	&lt;?php echo &#036;form-&gt;textField(&#036;model_login,'user_email',array('size'=&gt;60,'maxlength'=&gt;255)); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model_login,'user_email'); ?&gt;


&lt;/div&gt;


&lt;div class=&quot;row&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'First Name'); ?&gt;


	&lt;?php echo &#036;form-&gt;textField(&#036;model,'kash_firstName',array('size'=&gt;60,'maxlength'=&gt;255)); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'kash_firstName'); ?&gt;


&lt;/div&gt;





&lt;div class=&quot;row&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'LastName'); ?&gt;


	&lt;?php echo &#036;form-&gt;textField(&#036;model,'kash_lastName',array('size'=&gt;60,'maxlength'=&gt;255)); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'kash_lastName'); ?&gt;


&lt;/div&gt;











&lt;div class=&quot;row&quot;&gt;


&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'Country'); ?&gt;





&lt;?php echo &#036;form-&gt;dropDownList(&#036;model,'kash_country',CHtml::listData(Countrylist::model()-&gt;findAll(),'kash_counrtyId', 'kash_countryName'));?&gt;


&lt;?php echo &#036;form-&gt;error(&#036;model,'kash_country'); ?&gt;





	&lt;div class=&quot;row&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model_login,'password'); ?&gt;


	&lt;?php echo &#036;form-&gt;passwordField(&#036;model_login,'user_password',array('size'=&gt;60,'maxlength'=&gt;128)); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model_login,'password'); ?&gt;


&lt;/div&gt;





&lt;div class=&quot;row&quot;&gt;

<?php echo $form->label($model_login,‘PasswordConfirm’); ?>

<?php echo $form->passwordField($model_login,‘PasswordConfirm’,array(‘size’=>60,‘maxlength’=>256)); ?>

<?php echo $form->error($model_login,‘PasswordConfirm’); ?>

</div>

&lt;/div&gt;














&lt;div class=&quot;row buttons&quot;&gt;


	&lt;?php echo CHtml::submitButton(&#036;model-&gt;isNewRecord ? 'Register' : 'Save'); ?&gt;


&lt;/div&gt;

<?php $this->endWidget(); ?>

</div><!-- form -->

view\users\create.php file :

<?php

/* @var $this UsersController */

/* @var $model Users */

$this->breadcrumbs=array(

'Users'=&gt;array('index'),


'Create',

);

$this->menu=array(

array('label'=&gt;'List Users', 'url'=&gt;array('index')),


array('label'=&gt;'Manage Users', 'url'=&gt;array('admin')),

);

?>

<h1>Register</h1>

<?php $this->renderPartial(’_form’, array(‘model’=>$model,‘model_login’=>$model_login)); ?>

PLZ help me !! Thank you all

hello brother/sister you are simply amazing and your snippet is more readable :)

plz i want solution for this

you have two model say Model1, Model2 and you created the form controls properly for both models. you can try this in controller




actionInsert( ){

 $model1 = new Model1();

 $model2 = new Model2();

 if(isset($_POST['Model1'],$_POST['Model2'])

{

 $model1->attributes = $_POST['Model1'];

$model2->attributes = $_POST['Model2'];

 if($model1->validate() && $model2->validate()){

 $model1->save(false);

$model2->save(false);

}

}

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

 'model1'=>$model1,

 'model2'=>$model2

));

}


//in myForm create your form controls with activeform widget using appropriate models say $model1 and $model2



:rolleyes: :rolleyes: thanks a lot Ahamed bro, its working,my password repeat is not working and how to store password in db with encrypted form plz help.

thanks for ur help.

hello mannu in rules() add the following


rules(){

return array(

....

 array('password','compare','compareAttribute'=>'repeat_password')

....

);

}

// in controller

if($model->validate()){

 $model->password  = CPasswordHelper::hashPassword($model->password);

 $model->save(false);

}


//To verify a password, fetch the user's

saved hash from the database (into

$hash) and:

//$password user entered password.

//$hash the encrypted password stored in db

if (CPasswordHelper::verifyPassword($password, $hash))

    // password is good

else

    // password is bad



Note: here I am using yii 1.1.14. CPasswordHelper is available from this version only for more details refer here for encryption

that is not validating dear

post your action code and model rules using code button (<>) on the editor

model rule:





<?php

public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('business_name, business_email, business_country', 'required'),

			array('business_name','match','pattern' => '/^[a-zA-Z ]+$/'),

			array('business_email','unique','on'=>'create,update'),

			array('business_email','email'),

			array('business_country', 'numerical', 'integerOnly'=>true),

			array('business_name, business_email', 'length', 'max'=>255),

			

			

			// The following rule is used by search().

			// @todo Please remove those attributes that should not be searched.

			array('kash_business_user_id, business_name, business_email, business_phone, business_address, business_country, date_created, date_updated', 'safe', 'on'=>'search'),

		);

	}







controller action code

============




public function actionCreate()

	{

		$model=new BusinessUser;

		$model_login = new UserLogin;

		// Uncomment the following line if AJAX validation is needed

		 $this->performAjaxValidation($model);

		if(($_POST['UserLogin']['user_password']) === $_POST['UserLogin']['confirmPassword'])

		{

		   if(isset($_POST['BusinessUser'],$_POST['UserLogin']))

			{

			//$model->date_created = date('dd-mm-yyyy');

			

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

			

			$password = $_POST['UserLogin']['user_password'];

			 if (function_exists("openssl_random_pseudo_bytes") && strtoupper(substr(PHP_OS,0,3)) !== "WIN") {

                        $salt = openssl_random_pseudo_bytes(22);

                }

			else	

					$salt = mt_rand(22,24);

			$salt = '$2a$%13$' . strtr($salt, array('_'=>'.','~'=>'/'));

			$password_hashm = crypt($password,$salt); 

			$model_login->user_password = $password_hashm;

			$model_login->kash_usertype_id = '2';	

			$model_login->user_email = $_POST['BusinessUser']['business_email'];	

			

			

			

			/*&& $model_login->validate() */

			if($model->validate())

			{

				/* $model_login->user_password = CPasswordHelper::hashPassword($model_login->user_password); */

				if($model_login->save(false))

				{	

					$model->kash_user_login_id = $model_login->kash_user_login_id;

					if($model->save(false))

					$this->redirect('/kashpal/');		

				}	

			}

			else

				echo "Registration failed ! Try again.";

			

			

			

			}

		}

		else

		{

			echo "Confirm password should be same as Password !!";

		}

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

			'model'=>$model,

			'model_login'=>$model_login,

		));

	

	}

?>



i am using one controller of two model. not vallidating plz help,thank you a lot bro :rolleyes:

Hello mannu you are manually comparing the password with confirm_password don’t do like this. in your UserLogin model in rules() add the rule as I suggested before (refer my previous reply) and in the BusinessUser controller’s actionCreate() method do like this




actionCreate()

{

$model = new BusinessUser();

$login = new UserLogin();

if(isset($_POST['BusinessUser'],$_POST['UserLogin']))

{

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

$login -> attributes= $_POST ['UserLogin' ];

 if($model->validate() && $login->validate()){

//both models are valid do something

}

}

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

'model' => $model ,

'model_login' =>$login ,

));



Dear brother that I have done but not working, plz see my previous code, bcoz that was not working thats why i tried it mannualy