Update 2 Model Using One Form

hello i have 2 data table name as hotel table & hotelUser table

i want insert data in to hoteltable which available in hotelUser table when i update hotel user data it must insert both of table

additional( hotel user is tempory data table frist i insert data in to this table after check data by admin he click update button & send data to hotel table)

please solve me soon as…

thank you have nice day

Hi @channasmcs

Check this wiki

http://www.yiiframework.com/wiki/19/how-to-use-a-single-form-to-collect-data-for-two-or-more-models/

If you have any question, please tell me :)

1 Like

thank mr .KonApaz

this is my hotel & hotel_user table detail

[b]

HOTEL table[/b]

hotels (

hotel_id int(60) NOT NULL AUTO_INCREMENT,

type_id int(60) NOT NULL,

Rate_id int(60) NOT NULL,

hotel_name varchar(255) NOT NULL,

discription text NOT NULL,

image varchar(255) NOT NULL,

contact_detail text NOT NULL,

city_id int(60) NOT NULL,

latitute float NOT NULL,

lontute float NOT NULL,

metadata text NOT NULL,

[b]

Hotel_user

table[/b]

hotel_user (

hotel_id int(60) NOT NULL AUTO_INCREMENT,

[color="#FF0000"]username varchar(255) NOT NUL[/color]L,

type_id int(60) NOT NULL,

Rate_id int(60) NOT NULL,

hotel_name varchar(255) NOT NULL,

discription text NOT NULL,

image varchar(255) NOT NULL,

contact_detail text NOT NULL,

city_id int(60) NOT NULL,

latitute float NOT NULL,

lontute float NOT NULL,

metadata text NOT NULL,

see i have additional column in hotel_user table .

how i send data in hotel table with out username column ? :huh:

As long as I figured out that , You have two CActiverecord model Hotel and Hotel user. You want to collect input from one single form and save both the models . You can do it in below way :




public function actionCreate()

{

  $hotel=new Hotel;

  $hotelUser=new HotelUser;


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

  {

    $hotel->attributes=$_POST['HotelUser'];

    $hotelUser->attributes=$_POST['HotelUser'] //-- User $_POST['HotelUser'] for both model to load attributes

    $hotel->save();$hotelUser->save();

  }

$this->render('formView',array('model'=>$hotelUser)); // -- Pass hotelUser model to view for rendering form.

}



thanks bro…

did you see did you see in [color="#FF0000"]hotel User table[/color] have additional column name as Username when insert data how insert in to hotel table with out Username i pleasure if you can give me solution…?

Hi again channasmcs

Do you want to set the username with value that is not exists in form ?

In this case as the Chandrakanta post, add an extra line code like this


public function actionCreate()

{

  $hotel=new Hotel;

  $hotelUser=new HotelUser;


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

  {

    $hotel->attributes=$_POST['HotelUser'];

    $hotelUser->attributes=$_POST['HotelUser'] //-- User $_POST['HotelUser'] for both model to load attributes

    $hotel->save();

    $hotelUser->username = 'anything that you want by php or Yii code about username'

    $hotelUser->save();

  }

$this->render('formView',array('model'=>$hotelUser)); // -- Pass hotelUser model to view for rendering form.

}

if I didn’t understood exactly what you want, please give more information :)

hi i want save data in hotel table with out username(available in hotelUser table) because in hotel table doesn’t have username field

Hi channasmcs,

I think that Chandrakanta and KonApaz have already suggested you the solution that is good enough.

If you don’t get it, why don’t you post your current code for the controller action and the view?

this my controller (hoteluser)

public function actionCreate()

{


	$model=new HotelUser;


            


            





	// Uncomment the following line if AJAX validation is needed


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





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


	{


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


		//image upload


		$myfile=CUploadedFile::getInstance($model,'image');


		if (is_object($myfile) && get_class($myfile)==='CUploadedFile') {


			// get image with image path


			$model->image="http://10.0.2.2/TheGuidersite_service/images/Hotel/{$myfile->name}";


		}


		


		if($model->save())


		{ //save image URL


			$myfile->saveAs(Yii::app()->basePath.'/../images/Hotel/'.$myfile->name);  // image will uplode to rootDirectory/banner/


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


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


		


			


			


			$mail=Yii::app()->Smtpmail;


				


			$mail->SetFrom( 'onasha@bizappsi.com',$model->username);


			


			$msg=$model->username.'<br/>'.$model->hotel_name.'<br/>'.$model->discription .'<br/>'.$model->contact_detail.'<br/>'.'Thank you for insert Hotel detail . We will respond to you  soon as possible. ' ;


			//$mail->subject    = $subject->subject;


			$mail->MsgHTML($msg);


			$mail->AddAddress('onasha@bizappsi.com','programmer channa');


			$mail->AddAddress($model->username,'programmer channa');


			if(!$mail->Send()) {


			echo "Mailer Error: " . $mail->ErrorInfo;


				


			}else {


			


			echo "Thank you for insert Hotel detail . Please Check your mail";


			//Yii::app()->user->setFlash('','Thank you for contacting us. We will respond to you as soon as possible.');


			//$this->redirect(array('view','id'=>$model->hotel_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['HotelUser']))


	{


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


		$myfile=CUploadedFile::getInstance($model,'image');


		if (is_object($myfile) && get_class($myfile)==='CUploadedFile') {


			// get image with image path


			$model->image="http://10.0.2.2/TheGuidersite_service/images/Hotel/{$myfile->name}";


		}


		


		if($model->save())


			$myfile->saveAs(Yii::app()->basePath.'/../images/Hotel/'.$myfile->name);


			$mails=Yii::app()->Smtpmail;


				


			$mails->SetFrom( 'onasha@bizappsi.com',$model->username);


			


			$msg=$model->username.'<br/>'.$model->hotel_name.'<br/>'.'Congratulations we are add Your new Hotel detail' ;


			$mails->MsgHTML($msg);


			$mails->AddAddress('onasha@bizappsi.com','programmer channa');


			$mails->AddAddress($model->username,'programmer channa');


			if(!$mails->Send()) {


				echo "Mailer Error: " . $mails->ErrorInfo;


					


			}else {


			


				echo "Congratulations we  added Your new Hotel detail . ";


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


			}


			


			


	}





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


		'model'=>$model,


	));


            


            


}

[b]

model(hoteluser)[/b]

<?php

/**

  • This is the model class for table "hotel_user".

  • The followings are the available columns in table ‘hotel_user’:

  • @property integer $hotel_id

  • @property string $username

  • @property integer $type_id

  • @property integer $Rate_id

  • @property string $hotel_name

  • @property string $discription

  • @property string $image

  • @property string $contact_detail

  • @property integer $city_id

  • @property double $latitute

  • @property double $lontute

  • @property string $metadata

  • The followings are the available model relations:

  • @property Cities $city

  • @property TypeHotel $type

*/

class HotelUser extends CActiveRecord

{

/**


 * Returns the static model of the specified AR class.


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


 * @return HotelUser the static model class


 */


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


{


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


}





/**


 * @return string the associated database table name


 */


public function tableName()


{


	return 'hotel_user';


}





/**


 * @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('username, type_id, Rate_id, hotel_name, discription, image, contact_detail, city_id, latitute, lontute, metadata', 'required'),


		array('type_id, Rate_id, city_id', 'numerical', 'integerOnly'=&gt;true),


		array('latitute, lontute', 'numerical'),


		array('username, hotel_name, image', 'length', 'max'=&gt;255),


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


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


		array('hotel_id, username, type_id, Rate_id, hotel_name, discription, image, contact_detail, city_id, latitute, lontute, metadata', 'safe', 'on'=&gt;'search'),


	   	array('image', 'file','types'=&gt;'jpg, gif, png', 'allowEmpty'=&gt;true, 'on'=&gt;'update'),


		array(' image', 'length', 'max'=&gt;255, 'on'=&gt;'insert,update'),


	


	);


}





/**


 * @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(


		'city' =&gt; array(self::BELONGS_TO, 'Cities', 'city_id'),


		'type' =&gt; array(self::BELONGS_TO, 'TypeHotel', 'type_id'),


	);


}





/**


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


 */


public function attributeLabels()


{


	return array(


		'hotel_id' =&gt; 'Hotel',


		'username' =&gt; 'Username',


		'type_id' =&gt; 'Type',


		'Rate_id' =&gt; 'Rate',


		'hotel_name' =&gt; 'Hotel Name',


		'discription' =&gt; 'Discription',


		'image' =&gt; 'Image',


		'contact_detail' =&gt; 'Contact Detail',


		'city_id' =&gt; 'City',


		'latitute' =&gt; 'Latitute',


		'lontute' =&gt; 'Lontute',


		'metadata' =&gt; 'Metadata',


	);


}





/**


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


 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.


 */


public function search()


{


	// Warning: Please modify the following code to remove attributes that


	// should not be searched.





	&#036;criteria=new CDbCriteria;





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


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


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


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


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


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


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


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


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


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


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


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





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


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


	));


}

}

view(hoteluser)

<?php

/* @var $this HotelUserController */

/* @var $model HotelUser */

/* @var $form CActiveForm */

?>

<div class="form">

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

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


'enableAjaxValidation'=&gt;false,


	'htmlOptions' =&gt; array(


			'enctype' =&gt; 'multipart/form-data',


	),

)); ?>

&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,'username'); ?&gt;


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


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


&lt;/div&gt;





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


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


	&lt;?php echo &#036;form-&gt;dropDownList(&#036;model,'type_id',TypeHotel::model()-&gt;getTypeHoteloptions()); ?&gt;


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


&lt;/div&gt;





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


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


    &lt;?php echo &#036;form-&gt;dropDownList(&#036;model,'Rate_id',Rate::model()-&gt;getRateoptions()); ?&gt;


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


&lt;/div&gt;





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


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


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


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


&lt;/div&gt;





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


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


	&lt;?php echo &#036;form-&gt;textArea(&#036;model,'discription',array('rows'=&gt;6, 'cols'=&gt;50)); ?&gt;


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


&lt;/div&gt;





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


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


	&lt;?php echo CHtml::activeFileField(&#036;model, 'image'); ?&gt;


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


&lt;/div&gt;





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


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


	&lt;?php echo &#036;form-&gt;textArea(&#036;model,'contact_detail',array('rows'=&gt;6, 'cols'=&gt;50)); ?&gt;


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


&lt;/div&gt;





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


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


	 &lt;?php echo &#036;form-&gt;dropDownList(&#036;model,'city_id',Cities::model()-&gt;getcitiesoptions()); ?&gt;


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


&lt;/div&gt;





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


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


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


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


&lt;/div&gt;





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


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


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


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


&lt;/div&gt;





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


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


	&lt;?php echo &#036;form-&gt;textArea(&#036;model,'metadata',array('rows'=&gt;6, 'cols'=&gt;50)); ?&gt;


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


&lt;/div&gt;





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


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


&lt;/div&gt;

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

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

[b]

model(hoteltable)[/b]

<?php

/**

  • This is the model class for table "hotels".

  • The followings are the available columns in table ‘hotels’:

  • @property integer $hotel_id

  • @property integer $type_id

  • @property integer $Rate_id

  • @property string $hotel_name

  • @property string $discription

  • @property string $image

  • @property string $contact_detail

  • @property integer $city_id

  • @property double $latitute

  • @property double $lontute

  • @property string $metadata

  • The followings are the available model relations:

  • @property TypeHotel $type

  • @property Rate $rate

  • @property Cities $city

  • @property Places[] $places

*/

class Hotels extends CActiveRecord

{

/**


 * Returns the static model of the specified AR class.


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


 * @return Hotels the static model class


 */


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


{


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


}





/**


 * @return string the associated database table name


 */


public function tableName()


{


	return 'hotels';


}





/**


 * @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('type_id, Rate_id, hotel_name, discription, image, contact_detail, city_id, latitute, lontute, metadata', 'required'),


		array('type_id, Rate_id, city_id', 'numerical', 'integerOnly'=&gt;true),


		array('latitute, lontute', 'numerical'),


		array('hotel_name, image', 'length', 'max'=&gt;255),


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


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


		array('hotel_id, type_id, Rate_id, hotel_name, discription, image, contact_detail, city_id, latitute, lontute, metadata', 'safe', 'on'=&gt;'search'),


		array('image', 'file','types'=&gt;'jpg, gif, png', 'allowEmpty'=&gt;true, 'on'=&gt;'update'),


			array(' image', 'length', 'max'=&gt;255, 'on'=&gt;'insert,update'),


	);


}





/**


 * @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(


		'type' =&gt; array(self::BELONGS_TO, 'TypeHotel', 'type_id'),


		'rate' =&gt; array(self::BELONGS_TO, 'Rate', 'Rate_id'),


		'city' =&gt; array(self::BELONGS_TO, 'Cities', 'city_id'),


		'places' =&gt; array(self::HAS_MANY, 'Places', 'hotel_id'),


	);


}





/**


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


 */


public function attributeLabels()


{


	return array(


		'hotel_id' =&gt; 'Hotel',


		'type_id' =&gt; 'Type',


		'Rate_id' =&gt; 'Rate',


		'hotel_name' =&gt; 'Hotel Name',


		'discription' =&gt; 'Discription',


		'image' =&gt; 'Image',


		'contact_detail' =&gt; 'Contact Detail',


		'city_id' =&gt; 'City',


		'latitute' =&gt; 'Latitute',


		'lontute' =&gt; 'Lontute',


		'metadata' =&gt; 'Metadata',


	);


}





/**


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


 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.


 */


public function search()


{


	// Warning: Please modify the following code to remove attributes that


	// should not be searched.





	&#036;criteria=new CDbCriteria;





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


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


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


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


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


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


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


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


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


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


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





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


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


	));


}





 public function gethotelsoptions()


    {


        return CHtml::listData(Hotels::model()-&gt;findAll(),'hotel_id','hotel_name');


    }

}

above code is 100% work …thank you but when i insert data in to hotel table i not insert due to it dont have username field how i insert data in to hotel table from hotel user with out Username

thank guys finally i can fix this erorr sry make disturbe thank you have nice day…