modify in _form

I add additional textfields to _form as in line 25 these textfields accoring to another table t2 how I can store the entered values in t2 table.ie I want when I press create button to store original values(data in textfield which depend on t1) automatically store other field in t2 table

<div class="form">

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

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


'enableAjaxValidation'=&gt;false,

)); ?>

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


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


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


&lt;/div&gt;





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


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


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


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


&lt;/div&gt;





    ////////////////////////////////////////////////////////////////////////////////


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


        &lt;?php &#036;model= new T2;?&gt;


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


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


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


&lt;/div&gt;





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


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


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


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


&lt;/div&gt;





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


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


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


	&lt;?php echo &#036;form-&gt;error(&#036;model,'info'); ?&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 -->

You need to do this in your t1 controller. Ex: t1 = SubCategory && t2 = Category.




SubCategoryController


actionCreate()

{

    public function actionCreate()

    {

        $model = new SubCategory;


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

        {

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


            if ($model->save())

            {

                // You need to figure out how to get $parentId. Probably from form.

                $parentId = $_POST['blah']; OR $model->parentId OR query string.


                $parentCategory = Category::model->findByPk($parentId);

                $parentCategory->name = 'ccccc';

                $parentCategory->save();


                Yii::app()->user->setFlash('success', 'Sub Category successfully created.');

                $this->redirect(array('admin'));

            }

        }


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

            'model' => $model,

        ));

    }

}



Cheers,

Matt

Please with witch data I must change the following

$parentCategory = Category::model->findByPk([color="#FF0000"]$parentId[/color]);

            &#036;parentCategory-&gt;name = '[color=&quot;#FF0000&quot;]ccccc[/color]';

Please post both Models (t1 and t2), both controllers (t1controller and t2controller) and relevant views. Also, consider renaming your tables/models etc to something more human understandable.

Thanks,

Matt

thisl T1 model:




<?php


/**

 * This is the model class for table "t1".

 *

 * The followings are the available columns in table 't1':

 * @property integer $id2

 * @property string $f_name

 * @property string $l_name

 *

 * The followings are the available model relations:

 * @property T3[] $t3s

 */

class T1 extends CActiveRecord

{

	/**

	 * Returns the static model of the specified AR class.

	 * @return T1 the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 't1';

	}


	/**

	 * @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('id2, f_name, l_name', 'required'),

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

			array('f_name, l_name', 'length', 'max'=>33),

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

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

			array('id2, f_name, l_name', 'safe', 'on'=>'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(

			//'t3s' => array(self::MANY_MANY, 'T2', '''T1_id'),

                    // 't3s'=>array(self::HAS_ONE, 'T3','T1_id'),

 

	//'t3s' => array(self::HAS_MANY, 'T3', 'T1_id'),

		);

	}


	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'id2' => 'Id2',

			'f_name' => 'F Name',

			'l_name' => 'L Name',

		);

	}


	/**

	 * 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.


		$criteria=new CDbCriteria;


		$criteria->compare('id2',$this->id2);

		$criteria->compare('f_name',$this->f_name,true);

		$criteria->compare('l_name',$this->l_name,true);


		return new CActiveDataProvider(get_class($this), array(

			'criteria'=>$criteria,

		));

	}

}



this T2:




<?php


/**

 * This is the model class for table "t2".

 *

 * The followings are the available columns in table 't2':

 * @property integer $p_id

 * @property string $person

 * @property string $info

 *

 * The followings are the available model relations:

 * @property T3 $t3

 */

class T2 extends CActiveRecord

{

	/**

	 * Returns the static model of the specified AR class.

	 * @return T2 the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 't2';

	}


	/**

	 * @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('p_id, person, info', 'required'),

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

			array('person, info', 'length', 'max'=>33),

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

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

			array('p_id, person, info', 'safe', 'on'=>'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(

			//'t3' => array(self::HAS_ONE, 'T2', 'p_id'),

		);

	}


	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'p_id' => 'P',

			'person' => 'Person',

			'info' => 'Info',

		);

	}


	/**

	 * 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.


		$criteria=new CDbCriteria;


		$criteria->compare('p_id',$this->p_id);

		$criteria->compare('person',$this->person,true);

		$criteria->compare('info',$this->info,true);


		return new CActiveDataProvider(get_class($this), array(

			'criteria'=>$criteria,

		));

	}

}



this T1Controller:




<?php


class T1Controller 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

		);

	}


	/**

	 * 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('admin'),

			),

			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 T1;


		// Uncomment the following line if AJAX validation is needed

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


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

		{

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

			if($model->save())

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

		}


		$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['T1']))

		{

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

			if($model->save())

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

		}


		$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)

	{

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

		{

			// we only allow deletion via POST request

			$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'));

		}

		else

			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

	}


	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('T1');

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

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new T1('search');

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

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

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


		$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=T1::model()->findByPk((int)$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']==='t1-form')

		{

			echo CActiveForm::validate($model);

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

		}

	}

}



this T2Controller:




<?php


class T2Controller 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

		);

	}


	/**

	 * 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('admin'),

			),

			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 T2;


		// Uncomment the following line if AJAX validation is needed

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


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

		{

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

			if($model->save())

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

		{

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

			if($model->save())

				$this->redirect(array('view','id'=>$model->p_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)

	{

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

		{

			// we only allow deletion via POST request

			$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'));

		}

		else

			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

	}


	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('T2');

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

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new T2('search');

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

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

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


		$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=T2::model()->findByPk((int)$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']==='t2-form')

		{

			echo CActiveForm::validate($model);

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

		}

	}

}



t1 _form.php:




<div class="form">


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

	'id'=>'t1-form',

	'enableAjaxValidation'=>false,

)); ?>


	<p class="note">Fields with <span class="required">*</span> are required.</p>


	<?php echo $form->errorSummary($model); ?>


	<div class="row">

		<?php echo $form->labelEx($model,'id2'); ?>

		<?php echo $form->textField($model,'id2'); ?>

		<?php echo $form->error($model,'id2'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'f_name'); ?>

		<?php echo $form->textField($model,'f_name',array('size'=>33,'maxlength'=>33)); ?>

		<?php echo $form->error($model,'f_name'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'l_name'); ?>

		<?php echo $form->textField($model,'l_name',array('size'=>33,'maxlength'=>33)); ?>

		<?php echo $form->error($model,'l_name'); ?>

	</div>

           ////////////////////////////////////////////////////////////////////////////////

        <div class="row">

            <?php $model= new T2;?>

		<?php echo $form->labelEx($model,'p_id'); ?>

		<?php echo $form->textField($model,'p_id'); ?>

		<?php echo $form->error($model,'p_id'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'person'); ?>

		<?php echo $form->textField($model,'person',array('size'=>33,'maxlength'=>33)); ?>

		<?php echo $form->error($model,'person'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'info'); ?>

		<?php echo $form->textField($model,'info',array('size'=>33,'maxlength'=>33)); ?>

		<?php echo $form->error($model,'info'); ?>

	</div>

        /////////////////////////////////////////////////////////////////////////////////


	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

	</div>


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


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

NOW IS OK , and this is the correct create (any thing after comment don’t care with it it’s not necessary.




public function actionCreate()

	{

	$model = new T1; 

        $model2=new T2;

 

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

        { 

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

 

            if ($model->save()) 

            { 

                // You need to figure out how to get $parentId. Probably from form. 

          //      $parentId =$model->id2; 

 

              //  $model2 = T2::model()->findByPk($parentId); 

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

                $model2->save(); 

            //    Yii::app()->user->setFlash('success', 'Sub Category successfully created.'); 

              //  $this->redirect(array('admin'));

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

            } 

        } 

 

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

           'model' => $model,    )  ); 


	}



and this is correct form (textfield witch want to store them in another table must be as deferent model in my example $model2 as follow)




...

.

.

.

.

.

         ////////////////////////////////////////////////////////////////////////////////

           <?php $model2=new T2;?>

        <div class="row">

            <?php $model= new T2;?>

		<?php echo $form->labelEx($model2,'p_id'); ?>

		<?php echo $form->textField($model2,'p_id'); ?>

		<?php echo $form->error($model2,'p_id'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model2,'person'); ?>

		<?php echo $form->textField($model2,'person',array('size'=>33,'maxlength'=>33)); ?>

		<?php echo $form->error($model2,'person'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model2,'info'); ?>

		<?php echo $form->textField($model2,'info',array('size'=>33,'maxlength'=>33)); ?>

		<?php echo $form->error($model2,'info'); ?>

	</div>

        /////////////////////////////////////////////////////////////////////////////////

.....

.

.

.

.



Hi,

Ok, if it’s working; great.

But, I think you need to take a step back and look at your DB logic. From what I can see T1 table holds First Name and Last Name. T2 holds Person (not sure what string is going to be saved here - fullname?) and Info.

Each record in both tables seem to correlate to each other. Ex. T2.p_id = T1.id2. Is this correct - a 1 to 1 relationship? If so, I would create a single person table, represented by a single Person model.

Also, I’ll assume your p_id in T2 is a primary key; auto increment? why are you setting the Id manually in the form? Ignore it and let the DB handle the auto increment.


If indeed it is a child/parent relationship, the usual method is to have a dropdown list, hidden field, checkbox etc. of the parent’s id in the child form. Then, in the child’s controller, retrieve the parent’s id, and save it to the child record.

Thank you for your answer,

these tables are virtual table for training only ,they are not actual tables.

Thank you again