$model->save() problem

I am facing typical problem. When calling $model->save() from controller action, it is inserting two rows with same values instead of one.

its because of jquery or any javascript… remove some and try…

Paste your controller’ and model’ code.

Happy coding.

Controller code…




public function actionConfigDeviceReport() {

            $model=new DeviceReportList;

            $deviceListModel = DeviceList::model()->findAll();

            $deviceReportModel = DeviceReports::model()->findAll();

            $deviceCategoryModel = DeviceCategory::model()->findAll();


            // Uncomment the following line if AJAX validation is needed

            $this->performAjaxValidation($model);


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

            {

                $model->dev_config_rpt_id = $_POST['DeviceReportList']['dev_config_rpt_id'];

                $model->device_id = $_POST['DeviceReportList']['device_id'];

                $model->save();

            }


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

                    'model'=>$model,

                    'deviceListModel'=>$deviceListModel,

                    'deviceReportModel'=>$deviceReportModel,

                    'deviceCategoryModel'=>$deviceCategoryModel,

            ));

        }



And model code…




<?php


/**

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

 *

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

 * @property integer $dev_report_id

 * @property integer $device_id

 * @property integer $dev_config_rpt_id

 * @property string $dev_rpt_create_date

 * @property integer $electrician_id

 * @property string $elec_sign_ts

 * @property integer $supervisor_id

 * @property string $super_sign_ts

 * @property integer $engineer_id

 * @property string $engg_sign_ts

 * @property string $dev_rpt_status

 *

 * The followings are the available model relations:

 * @property DeviceList $device

 * @property DeviceReports $devConfigRpt

 */

class DeviceReportList extends CActiveRecord

{

	/**

	 * Returns the static model of the specified AR class.

	 * @param string $className active record class name.

	 * @return DeviceReportList the static model class

	 */

    

        protected function beforeSave() {

            print "Save called";

            return parent::beforeSave();

        }

        public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 'device_report_list';

	}


	/**

	 * @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('device_id, dev_config_rpt_id', 'required'),

			array('device_id, dev_config_rpt_id, electrician_id, supervisor_id, engineer_id', 'numerical', 'integerOnly'=>true),

			array('elec_sign_ts, super_sign_ts, engg_sign_ts', 'length', 'max'=>20),

			array('dev_rpt_status', 'length', 'max'=>45),

                        array('dev_rpt_create_date', 'safe'),

                        array('device_id', 'checkUnique1'),

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

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

			array('dev_report_id, device_id, dev_config_rpt_id, dev_rpt_create_date, electrician_id, supervisor_id, engineer_id, dev_rpt_status', '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(

			'device' => array(self::BELONGS_TO, 'DeviceList', 'device_id'),

			'devConfigRpt' => array(self::BELONGS_TO, 'DeviceReports', 'dev_config_rpt_id'),

		);

	}


	/**

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

	 */

	public function attributeLabels()

	{

		return array(

			'dev_report_id' => 'Dev Report',

			'device_id' => 'Device',

			'dev_config_rpt_id' => 'Dev Config Rpt',

			'dev_rpt_create_date' => 'Dec Rpt Create Date',

			'electrician_id' => 'Electrician',

			'elec_sign_ts' => 'Elec Sign Ts',

			'supervisor_id' => 'Supervisor',

			'super_sign_ts' => 'Super Sign Ts',

			'engineer_id' => 'Engineer',

			'engg_sign_ts' => 'Engg Sign Ts',

			'dev_rpt_status' => 'Dev Rpt Status',

		);

	}


	/**

	 * 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('dev_report_id',$this->dev_report_id);

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

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

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

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

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

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

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

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

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

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


		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

		));

	}

        

        public function checkUnique1($attributes, $params) { 

            $deviceID = $this->device_id;

            $devReportID = $this->dev_config_rpt_id;

            $criteria = new CDbCriteria();

            $criteria->compare('device_id', $deviceID);

            $criteria->compare('dev_config_rpt_id', $devReportID);

            $criteria->compare('dev_rpt_status', 'pending');

            $checkModel = DeviceReportList::model()->exists($criteria);

            //$checkModel = DeviceReportList::model()->exists('dev_rpt_status = :STS', array(':STS'=>'pending'));

            var_dump($checkModel);

            if($checkModel === true) {

                $this->addError('engineer_id', "Report already configured and marked as 'Pending'");            

            }

        }

}



You should probably post your view code too. I’d guess that you’re submitting the form twice somehow.

Here is my view code. To check whether i’m submitting twice, beforeSave() function is added which output “save called”. It seems save() called once only in this process.




<div id="testdiv"></div>


<div class="wide form">


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

	'id'=>'device-report-list-form',

	'enableAjaxValidation'=>true,

)); ?>


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


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

        

        <div class="row">

            <?php echo CHtml::label('Device Category', 'dev_category') ?>

            <?php echo CHtml::dropDownList('dev_category', 'Select',

                            CHtml::listData($deviceCategoryModel, 'device_category_id', 'device_name'),

                            array(

                                'prompt'=>'Select category...',

                                'ajax'=>array(

                                    'type'=>'POST',

                                    'url'=>CController::createUrl('pm/ajaxGetDevicesAndReports'),

                                    'success'=>'updateFields',

                                    'dataType'=>'json',

                                    //'update'=>  '#testdiv',

                                    //'update'=>  '#' . CHtml::activeId($model, 'device_id'),

                                ),

                            )

                    ); ?>

        </div>

        

        <script type="text/javascript">

            function updateFields(response) {

                <?php echo "$('#" .  CHtml::activeId($model, 'device_id') . "').html(response.opt1);"; ?>

                <?php echo "$('#" .  CHtml::activeId($model, 'dev_config_rpt_id') . "').html(response.opt2);"; ?>

            }

        </script>

        <div class="row">

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

		<?php echo $form->dropDownList($model, 'device_id', array(),

                        array(

                            'prompt'=>'Select device...',

                        )); 

                ?>

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

	</div>

        

        <div class="row">

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

		<?php /*echo $form->dropDownList($model, 'sys_config_rpt_id', 

                        CHtml::listData($systemReportModel, 'sys_config_rpt_id', 'sys_rpt_name'),

                        array(

                            'prompt'=>'Select report...',

                        )); */

                echo $form->dropDownList($model, 'dev_config_rpt_id',array(),

                        array(

                            'prompt'=>'Select report...',

                        ));

                

                ?>

                        

            </select>

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

	</div>

        

	<div class="row buttons">

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

                ?>

            

	</div>

        

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


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



Dear Samrat,

I am not sure of my suggestion would be helpful to you.

Can you please try the following;

Remove the line $model->save(); in your controller.

Replace it with following:




if($model->save())

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



‘someView’ may be view file for ‘DeviceReportList’.

You may redirect it wherever you want.

There was a problem in controller function ‘performAjaxValidation($model);’ which i have rectified. Now the problem is solved.