[Solved] Dropdownlist Change Event - 500 (Internal Server Error)

There are 3 Departments and 2 Facilities on my project.

Each department use 5 digits reference number but starts differently.

(Department - Facility = Reference Number)

Ops & Maint - CUQ = 10001

Ops & Maint - DPP = 30001

AIM - CUQ = 50001

AIM - DPP = 70001

Shutdown - CUQ = 80001

Shutdown - DPP = 90001

using this form:




<div class="form">


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

	'id'=>'scaffold-form',

	'enableAjaxValidation'=>false,

        'htmlOptions' => array('enctype' => 'multipart/form-data')

     )); ?>


	<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,'department_id'); ?>

		<?php echo $form->dropDownList($model,'department_id', Department::model()->getDepartmentOptions(), array('prompt'=>'Select Department')); ?>

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

	</div>

        

        <div class="row">

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

		<?php echo $form->dropDownList($model,'facility_id', Facility::model()->getFacilityOptions(), array('prompt'=>'Select Facility')); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->textField($model,'id',array('size'=>11,'maxlength'=>7)); ?>

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

	</div>       



after selecting a department_id and facility_id, is it possible to search database and populate the id(reference number) with the last reference number + 1 of the department-facilty selected using dropdownlist change event?

The reason I want to achieve this is because when creating a new scaffold, I don’t want to check what would be the next ref.# based on department - facilty serial instead it should be displayed automatically.

EDIT:

After selecting a department_id and facility_id then I got error; GET http://localhost/scaffreg/index.php/scaffold/newReferenceId?departmentId=1&facilityId=1 500 (Internal Server Error)on Chrome JavaScript console from the suggested code below.

Controller




public function actionNewReferenceId()

            {

                $departmentId=null;

                $facilityId=null;

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

                    $departmentId = $_GET['departmentId'];

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

                    $facilityId = $_GET['facilityId'];


                //generateRef is the function in $model that calculates the new reference based on the department and facility 

                $ref = Scaffold::generateRef($departmentId,$facilityId);


                if($ref>0)

                     echo CJSON::encode(

                        array(

                            'status'=>'success', 

                            'newReferenceID'=>$ref,

                    ));

                else

                     echo CJSON::encode(

                        array(

                            'status'=>'error',

                            'message'=>'Invalid reference generated', 

                            'newReferenceID'=>$ref,

                    ));

            }



Model




/*

         * returns generated reference if reference generated successfully, if not it returns 0

         */

        public static function generateRef($department_id,$facility_id){

                $newReference = 0;

                if($department_id && $facility_id){

                        $deptExists=Department::model()->exists('id=:id',array(':id',$department_id));

                        $facExists =Facility::model()->exists('id=:id',array(':id',$facility_id));

                        if($deptExists && $facExists){

                                $sql='SELECT max(id) as lastRef from tbl_scaffold where department_id=:dept_id and facility_id=:fac_id'; 

                                $command=Yii::app()->db->command($sql);

                                $command->bindParam(':dept_id',$department_id,PDO::PARAM_INT);

                                $command->bindParam(':fac_id',$facility_id,PDO::PARAM_INT);

                                $result= $command->queryRow();


                                if($result)

                                        $newReference =$result['lastRef']+1;

                                else{

                                        switch($department_id){

                                                case 1: //Ops & Maint

                                                        if($facility_id==1) //CUQ

                                                                $newReference=10001;

                                                        else if($facility_id==2) //DPP

                                                                $newReference=30001;

                                                         break;

                                                case 2: //AIMS

                                                        if($facility_id==1)

                                                                $newReference=50001;

                                                        else if($facility_id==2)

                                                                $newReference=70001;

                                                        break;

                                                case 3: //Shutdown

                                                        if($facility_id==1)

                                                                $newReference=80001;

                                                        else if($facility_id==2)

                                                                $newReference=90001;

                                                        break;


                                        }

                                }

                        }

                }

                return $newReference;

        }



View




<?php 

Yii::app()->clientScript->registerScript("newreference","

        $('#Scaffold_department_id, #Scaffold_facility_id').change(function(e){

        

                        var departmentId = $('#Scaffold_department_id').val();

                        var facilityId= $('#Scaffold_facility_id').val();

        

                        if(departmentId && facilityId){

                        var info = { departmentId:departmentId,

                        facilityId:facilityId

        };

        

                        $.ajax({

                        url: '" . Yii::app()->createUrl("/scaffold/newReferenceId") . "',

                        data: info,

                        type: 'GET',

                        dataType: 'json',                      

                        success:function(data){

                        if(data.status=='success')

                        $('#Scaffold_id').val(data.newReferenceID);

        },

        });

        

        }

        });

");

?>



Hi Charles,

Yes you could that but it requires communication between your view, controller and model.

[list=1]

[*]In your scaffolding model, you need a static function that

[list=1]

[*]accepts the dept ID and facility ID as paramaters

[*]checks that dept and facility ID are valid. If not valid, return 0 to the controller.

[*]grab the last reference_id from database that matches those parameters

[*] if a record exists, return the record’s reference+1 to controller.

[*]if there’s no matching record in the database then get the first five-digit number for that dept-facility and return the value to controller[/list]

[*]In your controller, you need an action that accepts an ajax request from your view, asks the static function for a new reference_id and then sends that id back to your view.

[*]In your view, the change event triggers an ajax request to the controller action and, if it gets a successful response, then the form’s reference_id field gets populated.

[/list]

Example (Rough guide)

Controller action




public function actionNewReferenceId(){

$departmentId=null;

$facilityId=null;

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

        $departmentId = $_GET['deptId'];

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

        $facilityId = $_GET['facilityId'];


//generateRef is the function in your model that calculates the new reference based on the dept and facility 

$ref = ScaffoldModelName::generateRef($departmentId,$facilityId);


if($ref>0)

 

     echo CJSON::encode(array(

                        'status'=>'success', 

                        'newReferenceID'=>$ref,

                        ));

   else

     echo CJSON::encode(array(

                        'status'=>'error',

                        'message'=>'Invalid reference generated', 

                        'newReferenceID'=>$ref,

 

                       ));

}




In your view, register your script:




$('#yourfacilityfieldID, #yourdepartmentfieldID').on('change',function(){


var deptId = $('#yourdepartmentfieldID').val();

var facilityId= $('#yourfacilityfieldID').val();


//trigger ajax request only if both dropdownlists have selected values.

if(deptID && facilityID){

 var info = { deptId: deptId,

facilityId:facilityId

};


$.ajax({

 type: 'GET',

 dataType: 'json',

 url: '/controllername/actionname',

 data: info,

 success:function(data){

 if(data.status=='success')

  $('#yourreferencefieldID').val(data.newReferenceID);//if reference generated then referencefield gets populated. 

 },

});

});



References

Creating new records using cjuidialog with ajax .

Javascript and AJAX with Yii

Thanks BlkRaven for your reply, sorry if I will ask again as I’m newbie to Yii and PHP.

What code should I put to this Scaffold model?




public function rules()

	{

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

		// will receive user inputs.

		return array(

			array('id, department_id, facility_id, location, type_id, duty_id, date_erected', 'required'),

			array('id, department_id, facility_id, type_id, duty_id, work_order, deluge_id, los_id, deboard_id', 'numerical', 'integerOnly'=>true),

                        array('duty_id', 'in', 'range'=>self::getAllowedDutyRange()),

                        array('deluge_id', 'in', 'range'=>self::getAllowedDelugeRange()),

                        array('los_id', 'in', 'range'=>self::getAllowedLosRange()),

                        array('deboard_id', 'in', 'range'=>self::getAllowedDeboardRange()), 

			array('weight, erect_manhrs, dismantle_manhrs', 'length', 'max'=>7),

			array('requested_by, built_by', 'length', 'max'=>64),

                        array('id', 'unique'),

                        array('material_list', 'file', 'types'=>'jpg,jpeg,doc,docx,xls,xlsx,pdf',

                                'maxSize'=>1024 * 1024 * 3, // 3MB

                                'tooLarge'=>'The file was larger than 3MB. Please upload a smaller file.',

                                'allowEmpty' => true),

                        array('inspection_date, date_dismantled', 'date', 'format'=>'yyyy-MM-dd', 'allowEmpty'=>true),

			array('status_id, other_details', 'safe'),

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

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

                        array('id, department_id, facility_id, location, type_id, duty_id, status_id, weight, work_order, erect_manhrs, dismantle_manhrs, date_erected, inspection_date, date_dismantled, requested_by, built_by, other_details, deluge_id, los_id, deboard_id, material_list, create_time, create_user_id, update_time, update_user_id', '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(

			'inspections' => array(self::HAS_MANY, 'Inspection', 'scaffold_id'),

			'updateUser' => array(self::BELONGS_TO, 'User', 'update_user_id'),

			'createUser' => array(self::BELONGS_TO, 'User', 'create_user_id'),

			'department' => array(self::BELONGS_TO, 'Department', 'department_id'),

			'facility' => array(self::BELONGS_TO, 'Facility', 'facility_id'),

			'type' => array(self::BELONGS_TO, 'Type', 'type_id'),

		);

	}


	/**

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

	 */

	public function attributeLabels()

	{

		return array(

                        'id' => 'Reference Number',

			'department_id' => 'Department Requestor',

                        'facility_id' => 'Facility',                 

			'location' => 'Location',

			'type_id' => 'Type of Scaffold',

			'duty_id' => 'Design Loading',

			'status_id' => 'Status',

			'weight' => 'Weight (Kg.)',

			'work_order' => 'Work Order',

			'erect_manhrs' => 'Manhours to Build',

			'dismantle_manhrs' => 'Manhours to Dismantle',

			'date_erected' => 'Date Erected',

			'inspection_date' => 'Next Inspection Due',

			'date_dismantled' => 'Date Dismantled',

			'requested_by' => 'Requested By',

			'built_by' => 'Built By',

                        'other_details' => 'Other Details',

			'deluge_id' => 'Blocking Deluge?',

			'los_id' => 'Blocking LOS?',

			'deboard_id' => 'Deboarded?',

                        'material_list' => 'Material List',

			'create_time' => 'Create Time',

			'create_user_id' => 'Create User',

			'update_time' => 'Update Time',

			'update_user_id' => 'Update User',                    

		);

	}


	/**

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 

		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

                        'sort' => array(

                            'defaultOrder' => 'id DESC',

                       ),

                        /*'pagination' => array(

                            'pageSize' => 10,

                       ),*/

                ));

	}



and which scaffold view should I register the script? Thanks in advance.

I’ll try my best. For the purposes of providing an example, I’ve hard-coded some values (not good practice).

Where I have written the facility/department name, it needs the actual id.




/**

 * returns generated reference if reference generated successfully, if not, it returns 0

 */


public static function generateRef($dept_id,$facility_id){

	$newReference = 0;

	if($dept_id && $facility_id){

		$deptExists=Department::model()->exists('id=:id',array(':id',$dept_id));

		$facExists =Facility::model()->exists('id=:id',array(':id',$facility_id));

		if($deptExists && $facExists){

			$sql='SELECT max(reference) as lastRef from {{Scaffold}} where department_id=:dept_id and facility_id=:fac_id';//where Scaffold is the name of your 'scaffold' model

			$command=Yii::app()->db->command($sql);

			$command->bindParam(':dept_id',$dept_id,PDO::PARAM_INT);

			$command->bindParam(':fac_id',$facility_id,PDO::PARAM_INT);

			$result= $command->queryRow();


			if($result)

				$newReference +=$result['lastRef'];

			else{

				switch($dept_id){

					case 'Ops & Maint':

						if($facility_id=='CUQ')

							$newReference=10001;

						else if($facility_id=='DPP')

							$newReference=30001;

			  	break;

					case 'AIM':

						if($facility_id=='CUQ')

							$newReference=50001;

						else if($facility_id=='DPP')

							$newReference=70001;

						break;

					case 'Shutdown':

						if($facility_id=='CUQ')

							$newReference=80001;

						else if($facility_id=='DPP')

							$newReference=90001;

						break;


				}

			}

		}

	}

	return $newReference;

}



Not tested.

See Yii tutorial on ‘Working with databases’

In the ‘create’ view, I think.

Thank You BlkRaven for your BIG help.

I tried to register and play around with the code but I can’t make it work.

I’m getting an error




Syntax error 

 unexpected:	(

 after:	$

 expected:	variable, {, $ 



on my PHP IDE with line




 $('#facility_id, #department_id').on('change',function(){



create view




<?php

/* @var $this ScaffoldController */

/* @var $model Scaffold */


$this->breadcrumbs=array(

	'Scaffolds'=>array('index'),

	'Create',

);


$this->menu=array(

	array('label'=>'List Scaffold', 'url'=>array('index')),

	array('label'=>'Manage Scaffold', 'url'=>array('admin')),

);


Yii::app()->clientScript->registerScript(

$('#facility_id, #department_id').on('change',function(){


var departmentId = $('#department_id').val();

var facilityId= $('#facility_id').val();


//trigger ajax request only if both dropdownlists have selected values.

if(departmentID && facilityID){

 var info = { departmentId: departmentId,

facilityId:facilityId

};


$.ajax({

 type: 'GET',

 dataType: 'json',

 url: '/ScaffoldController/NewReferenceId',

 data: info,

 success:function(data){

 if(data.status=='success')

  $('#id').val(data.newReferenceID);//if reference generated then id gets populated. 

 },

});

};

});

);

?>


<h1>Create Scaffold</h1>


<?php echo $this->renderPartial('_form', array('model'=>$model)); ?>



You are welcome. When registering a script, you need to pass the function an id and your javascript code as strings like so:




<?php 


Yii::app()->clientScript->registerScript("newreference","

$('#facility_id, #department_id').on('change',function(){


var departmentId = $('#department_id').val();

var facilityId= $('#facility_id').val();


//trigger ajax request only if both dropdownlists have selected values.

if(departmentID && facilityID){

 var info = { departmentId: departmentId,

facilityId:facilityId

};


$.ajax({

 type: 'GET',

 dataType: 'json',

 url: '/scaffold/NewReferenceId',//the 'controller' part of the name is not needed.

 data: info,

 success:function(data){

 if(data.status=='success')

  $('#id').val(data.newReferenceID);//if reference generated then id gets populated. 

 },

});

};

});

);

");


?>



I think I’m almost there, there’s no error however no result either when selecting department and facility from create scaffold page.

Controller:




public function actionNewReferenceId()

            {

                $departmentId=null;

                $facilityId=null;

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

                    $departmentId = $_GET['departmentId'];

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

                    $facilityId = $_GET['facilityId'];


                //generateRef is the function in $model that calculates the new reference# based on the department and facility 

                $ref = Scaffold::generateRef($departmentId,$facilityId);


                if($ref>0)

                     echo CJSON::encode(

                        array(

                            'status'=>'success', 

                            'newReferenceID'=>$ref,

                    ));

                else

                     echo CJSON::encode(

                        array(

                            'status'=>'error',

                            'message'=>'Invalid reference generated', 

                            'newReferenceID'=>$ref,

                    ));

            }



Model:




/*

         * returns generated reference# if reference# generated successfully, if not it returns 0

         */

        public static function generateRef($department_id,$facility_id){

                $newReference = 0;

                if($department_id && $facility_id){

                        $deptExists=Department::model()->exists('id=:id',array(':id',$department_id));

                        $facExists =Facility::model()->exists('id=:id',array(':id',$facility_id));

                        if($deptExists && $facExists){

                                $sql='SELECT max(id) as lastRef from {{Scaffold}} where department_id=:dept_id and facility_id=:fac_id';//where Scaffold is the name of your 'scaffold' model

                                $command=Yii::app()->db->command($sql);

                                $command->bindParam(':dept_id',$department_id,PDO::PARAM_INT);

                                $command->bindParam(':fac_id',$facility_id,PDO::PARAM_INT);

                                $result= $command->queryRow();


                                if($result)

                                        $newReference +=$result['lastRef'];

                                else{

                                        switch($department_id){

                                                case 'Ops & Maint':

                                                        if($facility_id=='CUQ')

                                                                $newReference=10001;

                                                        else if($facility_id=='DPP')

                                                                $newReference=30001;

                                                         break;

                                                case 'AIM':

                                                        if($facility_id=='CUQ')

                                                                $newReference=50001;

                                                        else if($facility_id=='DPP')

                                                                $newReference=70001;

                                                        break;

                                                case 'Shutdown':

                                                        if($facility_id=='CUQ')

                                                                $newReference=80001;

                                                        else if($facility_id=='DPP')

                                                                $newReference=90001;

                                                        break;


                                        }

                                }

                        }

                }

                return $newReference;

        }



There are few things I noticed, it’s $departmentId & $facilityId / $newReferenceID on controller then $department_id and $facility_id / $newReference on model but sometimes it’s $departmentID & $facilityID on view.

Is it not case sensitive? I will try to make it the same across the board and see if I will get a positive result.

Still not working, Please help.

Hi

I’m sorry for the delay in responding. Had a deadline to meet.

The script is looking for the ‘department_id’ but, looking at the form you posted earlier, you don’t have ‘department_id’ explicitly set as the id for the ‘department_id’ attribute. This means that the event isn’t getting attached so nothing is happening. See this thread on how ids are generated.

Try this code and see if it works. I’ve made a few changes:


<?php 


Yii::app()->clientScript->registerScript("newreference","

	$('#Scaffold_facility_id, #Scaffold_department_id').on('change',function(){

	

			var departmentId = $('#Scaffold_department_id').val();

			var facilityId= $('#Scaffold_facility_id').val();

	

			//trigger ajax request only if both dropdownlists have selected values.

			if(departmentId && facilityId){

			var info = { departmentId: departmentId,

			facilityId:facilityId

	};

	

			$.ajax({

			type: 'GET',

			dataType: 'json',

			url: '/scaffold/newReferenceId',//the 'controller' part of the name is not needed.

			data: info,

			success:function(data){

			if(data.status=='success')

			$('#Scaffold_id').val(data.newReferenceID);//if reference generated then id gets populated.

	},

	});

	

	}

	});

");


?>



I just noticed there was an error in the code I gave you for your model. Please change this line:




  $newReference +=$result['lastRef']; //this will never increase



to


$newReference =$result['lastRef']+1;

Thank You So Much for your patience and kindness to help me resolve my queries.

Unfortunately the codes isn’t working yet.

By the way I’m developing my project on:

Netbeans 7.3.1

Yii 1.1.14

Apache/2.4.4 (Win64) PHP/5.5.1

Server version: 5.6.12-log - MySQL Community Server (GPL)

Please check if I put your codes on the right spot.

ScaffoldController:




<?php


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

		);

	}


	/**

	 * Displays a particular model.

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

	 */

	public function actionView($id)

	{

            $inspectionDataProvider=new CActiveDataProvider('Inspection', array(

			'criteria'=>array(

		 		'condition'=>'scaffold_id=:scaffoldId',

		 		'params'=>array(':scaffoldId'=>$this->loadModel($id)->id),

		 	),

                        'sort'=>array(

                            'defaultOrder'=>'id DESC',

                        ),

		 	'pagination'=>array(

		 		'pageSize'=>1,

		 	),

		 ));

		            

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

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

                        'inspectionDataProvider'=>$inspectionDataProvider,

		));

	}

      

	/**

	 * Creates a new model.

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

	 */               

	public function actionCreate()

	{

		$model=new Scaffold;

                $model->date_erected = date('Y-m-d');


		// Uncomment the following line if AJAX validation is needed

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


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

		{

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

                            if($filez=$this->uploadMultifile($model,'material_list','/uploads/materials/'))

                                {

                                $model->material_list=implode(",", $filez);

                                }

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

		{

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

                            if($filez=$this->uploadMultifile($model,'material_list','/uploads/materials/'))

                                {

                                $model->material_list=implode(",", $filez);

                                }

			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('Scaffold',array(

                    'sort'=>array(

                        'defaultOrder'=>'id DESC',                       

                    )

                ));

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

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new Scaffold('search');

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

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

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


		$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 $id the ID of the model to be loaded

	 * @return Scaffold the loaded model

	 * @throws CHttpException

	 */

	public function loadModel($id)

	{

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

		if($model===null)

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

		return $model;

	}


	/**

	 * Performs the AJAX validation.

	 * @param Scaffold $model the model to be validated

	 */

	protected function performAjaxValidation($model)

	{

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

		{

			echo CActiveForm::validate($model);

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

		}

	}

        

        public function uploadMultifile ($model,$attr,$path)

            {

                if($sfile=CUploadedFile::getInstances($model, $attr)){

                  foreach ($sfile as $i=>$file){  

                     $formatName=time().$i.'.'.$file->getExtensionName();

                     $file->saveAs(Yii::app()->basePath .DIRECTORY_SEPARATOR.'..'. $path.$formatName);

                     $ffile[$i]=$formatName;

                     }

                    return ($ffile);

                 }

             }

             

        public function actionNewReferenceId()

            {

                $departmentId=null;

                $facilityId=null;

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

                    $departmentId = $_GET['departmentId'];

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

                    $facilityId = $_GET['facilityId'];


                //generateRef is the function in $model that calculates the new reference based on the department and facility 

                $ref = Scaffold::generateRef($departmentId,$facilityId);


                if($ref>0)

                     echo CJSON::encode(

                        array(

                            'status'=>'success', 

                            'newReferenceID'=>$ref,

                    ));

                else

                     echo CJSON::encode(

                        array(

                            'status'=>'error',

                            'message'=>'Invalid reference generated', 

                            'newReferenceID'=>$ref,

                    ));

            }             

}



Scaffold (model)




<?php


/**

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

 *

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

 * @property integer $id

 * @property integer $department_id

 * @property integer $facility_id

 * @property string $location

 * @property integer $type_id

 * @property integer $duty_id

 * @property integer $status_id

 * @property string $weight

 * @property integer $work_order

 * @property string $erect_manhrs

 * @property string $dismantle_manhrs

 * @property string $date_erected

 * @property string $inspection_date

 * @property string $date_dismantled

 * @property string $requested_by

 * @property string $built_by

 * @property string $other_details

 * @property integer $deluge_id

 * @property integer $los_id

 * @property integer $deboard_id

 * @property string $material_list

 * @property string $create_time

 * @property integer $create_user_id

 * @property string $update_time

 * @property integer $update_user_id

 *

 * The followings are the available model relations:

 * @property Inspection[] $inspections

 * @property User $updateUser

 * @property User $createUser

 * @property Department $department

 * @property Facility $facility

 * @property Type $type

 */

class Scaffold extends ScaffRegActiveRecord

{    

    const DUTY_VERY='1';

    const DUTY_LIGHT='2';

    const DUTY_MEDIUM='3';

    const DUTY_HEAVY='4';

    const DUTY_SPECIAL='5';

    

    const STATUS_GREEN='1';

    const STATUS_RED='2';

    const STATUS_DISMANTLED='3';


    const DELUGE_NO='1';

    const DELUGE_YES='2';

    

    const LOS_NO='1';

    const LOS_YES='2';

    

    const DEBOARD_NO='1';

    const DEBOARD_YES='2';

    

	/**

	 * Returns the static model of the specified AR class.

	 * @param string $className active record class name.

	 * @return Scaffold 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 'tbl_scaffold';

	}


	/**

	 * @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('id, department_id, facility_id, location, type_id, duty_id, date_erected', 'required'),

			array('id, department_id, facility_id, type_id, duty_id, work_order, deluge_id, los_id, deboard_id', 'numerical', 'integerOnly'=>true),

                        array('duty_id', 'in', 'range'=>self::getAllowedDutyRange()),

                        array('deluge_id', 'in', 'range'=>self::getAllowedDelugeRange()),

                        array('los_id', 'in', 'range'=>self::getAllowedLosRange()),

                        array('deboard_id', 'in', 'range'=>self::getAllowedDeboardRange()), 

			array('weight, erect_manhrs, dismantle_manhrs', 'length', 'max'=>7),

			array('requested_by, built_by', 'length', 'max'=>64),

                        array('id', 'unique'),

                        array('material_list', 'file', 'types'=>'jpg,jpeg,doc,docx,xls,xlsx,pdf',

                                'maxSize'=>1024 * 1024 * 3, // 3MB

                                'tooLarge'=>'The file was larger than 3MB. Please upload a smaller file.',

                                'allowEmpty' => true),

                        array('inspection_date, date_dismantled', 'date', 'format'=>'yyyy-MM-dd', 'allowEmpty'=>true),

			array('status_id, other_details', 'safe'),

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

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

                        array('id, department_id, facility_id, location, type_id, duty_id, status_id, weight, work_order, erect_manhrs, dismantle_manhrs, date_erected, inspection_date, date_dismantled, requested_by, built_by, other_details, deluge_id, los_id, deboard_id, material_list, create_time, create_user_id, update_time, update_user_id', '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(

			'inspections' => array(self::HAS_MANY, 'Inspection', 'scaffold_id'),

			'updateUser' => array(self::BELONGS_TO, 'User', 'update_user_id'),

			'createUser' => array(self::BELONGS_TO, 'User', 'create_user_id'),

			'department' => array(self::BELONGS_TO, 'Department', 'department_id'),

			'facility' => array(self::BELONGS_TO, 'Facility', 'facility_id'),

			'type' => array(self::BELONGS_TO, 'Type', 'type_id'),

		);

	}


	/**

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

	 */

	public function attributeLabels()

	{

		return array(

                        'id' => 'Reference Number',

			'department_id' => 'Department Requestor',

                        'facility_id' => 'Facility',                 

			'location' => 'Location',

			'type_id' => 'Type of Scaffold',

			'duty_id' => 'Design Loading',

			'status_id' => 'Status',

			'weight' => 'Weight (Kg.)',

			'work_order' => 'Work Order',

			'erect_manhrs' => 'Manhours to Build',

			'dismantle_manhrs' => 'Manhours to Dismantle',

			'date_erected' => 'Date Erected',

			'inspection_date' => 'Next Inspection Due',

			'date_dismantled' => 'Date Dismantled',

			'requested_by' => 'Requested By',

			'built_by' => 'Built By',

                        'other_details' => 'Other Details',

			'deluge_id' => 'Blocking Deluge?',

			'los_id' => 'Blocking LOS?',

			'deboard_id' => 'Deboarded?',

                        'material_list' => 'Material List',

			'create_time' => 'Create Time',

			'create_user_id' => 'Create User',

			'update_time' => 'Update Time',

			'update_user_id' => 'Update User',                    

		);

	}


	/**

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 

		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

                        'sort' => array(

                            'defaultOrder' => 'id DESC',

                       ),

                        /*'pagination' => array(

                            'pageSize' => 10,

                       ),*/

                ));

	}

       

        public function getDutyOptions()

	{

		return array(

                    self::DUTY_VERY=>'Very Light Duty',

                    self::DUTY_LIGHT=>'Light Duty',

                    self::DUTY_MEDIUM=>'Medium Duty',

                    self::DUTY_HEAVY=>'Heavy Duty',

                    self::DUTY_SPECIAL=>'Special Duty',

		);

	}

	

	public function getAllowedDutyRange()

	{

		return array(

                    self::DUTY_VERY,

                    self::DUTY_LIGHT,

                    self::DUTY_MEDIUM,

                    self::DUTY_HEAVY,

                    self::DUTY_SPECIAL,

		);

	}


         public function getStatusOptions()

	{

		return array(

                    self::STATUS_GREEN=>'Green Tag',

                    self::STATUS_RED=>'Red Tag',

                    self::STATUS_DISMANTLED=>'Dismantled',

		);

	}


        public function getDelugeOptions()

	{

		return array(

                    self::DELUGE_NO=>'No',

                    self::DELUGE_YES=>'Yes',

		);

	}

	

	public function getAllowedDelugeRange()

	{

		return array(

                    self::DELUGE_NO,

                    self::DELUGE_YES,

		);

	}

        

        public function getLosOptions()

	{

		return array(

                    self::LOS_NO=>'No',

                    self::LOS_YES=>'Yes',

		);

	}

	

	public function getAllowedLosRange()

	{

		return array(

                    self::LOS_NO,

                    self::LOS_YES,

		);

	}

        

         public function getDeboardOptions()

	{

		return array(

                    self::DEBOARD_NO=>'No',

                    self::DEBOARD_YES=>'Yes',

		);

	}

	

	public function getAllowedDeboardRange()

	{

		return array(

                    self::DEBOARD_NO,

                    self::DEBOARD_YES,

		);

	}

        

        public function getDutyText()

	{

		$dutyOptions=$this->dutyOptions;

		return isset($dutyOptions[$this->duty_id]) ? $dutyOptions[$this->duty_id] : "unknown duty ({$this->duty_id})";

	}


        public function getStatusText()

	{

		$statusOptions=$this->statusOptions;

                return isset($statusOptions[$this->status_id]) ? $statusOptions[$this->status_id] : "* Create Inspection to Set Status *";

	}


        public function getDelugeText()

	{

		$delugeOptions=$this->delugeOptions;

		return isset($delugeOptions[$this->deluge_id]) ? $delugeOptions[$this->deluge_id] : "unknown deluge ({$this->deluge_id})";

	}

        

        public function getLosText()

	{

		$losOptions=$this->losOptions;

		return isset($losOptions[$this->los_id]) ? $losOptions[$this->los_id] : "unknown los ({$this->los_id})";

	}

        

        public function getDeboardText()

	{

		$deboardOptions=$this->deboardOptions;

		return isset($deboardOptions[$this->deboard_id]) ? $deboardOptions[$this->deboard_id] : "unknown deboard ({$this->deboard_id})";

	}


        /*

         * returns generated reference if reference generated successfully, if not it returns 0

         */

        public static function generateRef($department_id,$facility_id){

                $newReference = 0;

                if($department_id && $facility_id){

                        $deptExists=Department::model()->exists('id=:id',array(':id',$department_id));

                        $facExists =Facility::model()->exists('id=:id',array(':id',$facility_id));

                        if($deptExists && $facExists){

                                $sql='SELECT max(id) as lastRef from {{Scaffold}} where department_id=:dept_id and facility_id=:fac_id';//where Scaffold is the name of 'scaffold' model

                                $command=Yii::app()->db->command($sql);

                                $command->bindParam(':dept_id',$department_id,PDO::PARAM_INT);

                                $command->bindParam(':fac_id',$facility_id,PDO::PARAM_INT);

                                $result= $command->queryRow();


                                if($result)

                                        $newReference =$result['lastRef']+1;

                                else{

                                        switch($department_id){

                                                case 'Ops & Maint':

                                                        if($facility_id=='CUQ')

                                                                $newReference=10001;

                                                        else if($facility_id=='DPP')

                                                                $newReference=30001;

                                                         break;

                                                case 'AIM':

                                                        if($facility_id=='CUQ')

                                                                $newReference=50001;

                                                        else if($facility_id=='DPP')

                                                                $newReference=70001;

                                                        break;

                                                case 'Shutdown':

                                                        if($facility_id=='CUQ')

                                                                $newReference=80001;

                                                        else if($facility_id=='DPP')

                                                                $newReference=90001;

                                                        break;


                                        }

                                }

                        }

                }

                return $newReference;

        }

}



Create view




<?php

/* @var $this ScaffoldController */

/* @var $model Scaffold */


$this->breadcrumbs=array(

	'Scaffolds'=>array('index'),

	'Create',

);


$this->menu=array(

	array('label'=>'List Scaffold', 'url'=>array('index')),

	array('label'=>'Manage Scaffold', 'url'=>array('admin')),

);

?>


<?php 


Yii::app()->clientScript->registerScript("newreference","

	$('#Scaffold_facility_id, #Scaffold_department_id').on('change',function(){

	

			var departmentId = $('#Scaffold_department_id').val();

			var facilityId= $('#Scaffold_facility_id').val();

	

			//trigger ajax request only if both dropdownlists have selected values.

			if(departmentId && facilityId){

			var info = { departmentId: departmentId,

			facilityId:facilityId

	};

	

			$.ajax({

			type: 'GET',

			dataType: 'json',

			url: '/scaffold/newReferenceId',//the 'controller' part of the name is not needed.

			data: info,

			success:function(data){

			if(data.status=='success')

			$('#Scaffold_id').val(data.newReferenceID);//if reference generated then id gets populated.

	},

	});

	

	}

	});

");


?>


<h1>Create Scaffold</h1>


<?php echo $this->renderPartial('_form', array('model'=>$model)); ?>



and the _form view




<?php

/* @var $this ScaffoldController */

/* @var $model Scaffold */

/* @var $form CActiveForm */

?>


<div class="form">

    

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

	'id'=>'scaffold-form',

	'enableAjaxValidation'=>false,

        'htmlOptions' => array('enctype' => 'multipart/form-data')

     )); ?>


	<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,'date_erected'); ?>

		<?php $this->widget('zii.widgets.jui.CJuiDatePicker',

                        array(

                            'attribute' => 'date_erected',

                            'model' => $model,

                            // additional javascript options for the date picker plugin

                            'options' => array(

                                //'autoSize' => true,

                                'showAnim' => 'slideDown',

                                'showOn' => 'button',

                                'changeMonth' => true,

                                'changeYear' => true,

                                'dateFormat' => 'yy-mm-dd',

                            ),

                            'htmlOptions' => array(

                                'style' => 'height:20px;',

                            ),

                    ));?>

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

	</div>

        

	<div class="row">

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

		<?php echo $form->dropDownList($model,'department_id', Department::model()->getDepartmentOptions(), array('prompt'=>'Select Department')); ?>

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

	</div>

        

        <div class="row">

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

		<?php echo $form->dropDownList($model,'facility_id', Facility::model()->getFacilityOptions(), array('prompt'=>'Select Facility')); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->textField($model,'id',array('size'=>11,'maxlength'=>7)); ?>

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

	</div>

	

	<div class="row">

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

		<?php echo $form->textArea($model,'location',array('rows'=>6, 'cols'=>50)); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->dropDownList($model,'type_id', Type::model()->getTypeOptions(), array('prompt'=>'Select Scaffold Type')); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->dropDownList($model,'duty_id', $model->getDutyOptions(), array('prompt'=>'Select Design Loading')); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->textField($model,'weight',array('size'=>11,'maxlength'=>7)); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->textField($model,'work_order',array('size'=>11,'maxlength'=>7)); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->textField($model,'erect_manhrs',array('size'=>11,'maxlength'=>7)); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->textField($model,'dismantle_manhrs',array('size'=>11,'maxlength'=>7)); ?>

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

	</div>

	

	<div class="row">

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

		<?php echo $form->textField($model,'requested_by',array('size'=>60,'maxlength'=>64)); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->textField($model,'built_by',array('size'=>60,'maxlength'=>64)); ?>

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

	</div>

        

        <div class="row">

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

		<?php echo $form->textArea($model,'other_details',array('rows'=>6, 'cols'=>50)); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->dropDownList($model,'deluge_id', $model->getDelugeOptions()); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->dropDownList($model,'los_id', $model->getLosOptions()); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->dropDownList($model,'deboard_id', $model->getDeboardOptions()); ?>

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

	</div>

        

        <div class="row">

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

                <?php  $this->widget('CMultiFileUpload',

                    array(

                         'model' => $model,

                         'attribute' => 'material_list',

                         'accept' => 'jpg|jpeg|doc|docx|xls|xlsx|pdf',

                         'denied' => 'Only jpg,jpeg,doc,docx,xls,xlsx and pdf are allowed', 

                         'max' => 3,

                         'remove' => '[x]',

                         'duplicate' => 'Already Selected',


                ));?>

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

                <div class="hint">You can upload up to 3 attachments. </div>

        </div>

        

	<div class="row buttons">

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

	</div>


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


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



Again, Thank You for your endless support.

Hi Charles,

In your model

Can you replace this line:




$sql='SELECT max(id) as lastRef from {{Scaffold}} where department_id=:dept_id and facility_id=:fac_id';//where Scaffold is the name of 'scaffold' model



to




$sql='SELECT max(id) as lastRef from tbl_scaffold where department_id=:dept_id and facility_id=:fac_id'; 

Are you getting any error messages? In the form, are the events getting attached?

Edit:

Just noticed something else…When I posted the generateRef() function to place in your model, I explained that where I’ve written the facility/department name (eg ‘Ops & Maint’ or ‘CUQ’), you need to replace it with the actual department or facility id. The dropdown list in your form will be sending the actual id, not the name, to the controller.

So, for example, in this code from the generateRef() in your model:




...

case 'Ops & Maint': 

if($facility_id=='CUQ')

...



‘Ops & Maint’ is the name, not the id, of the department and ‘CUQ’ is the facility’s name. You need to replace all the departments and facilities with the actual id.

Hi BlkRaven,

Model with changes:




/*

         * returns generated reference if reference generated successfully, if not it returns 0

         */

        public static function generateRef($department_id,$facility_id){

                $newReference = 0;

                if($department_id && $facility_id){

                        $deptExists=Department::model()->exists('id=:id',array(':id',$department_id));

                        $facExists =Facility::model()->exists('id=:id',array(':id',$facility_id));

                        if($deptExists && $facExists){

                                $sql='SELECT max(id) as lastRef from tbl_scaffold where department_id=:dept_id and facility_id=:fac_id'; 

                                $command=Yii::app()->db->command($sql);

                                $command->bindParam(':dept_id',$department_id,PDO::PARAM_INT);

                                $command->bindParam(':fac_id',$facility_id,PDO::PARAM_INT);

                                $result= $command->queryRow();


                                if($result)

                                        $newReference =$result['lastRef']+1;

                                else{

                                        switch($department_id){

                                                case 1: //Ops & Maint

                                                        if($facility_id==1) //CUQ

                                                                $newReference=10001;

                                                        else if($facility_id==2) //DPP

                                                                $newReference=30001;

                                                         break;

                                                case 2: //AIMS

                                                        if($facility_id==1)

                                                                $newReference=50001;

                                                        else if($facility_id==2)

                                                                $newReference=70001;

                                                        break;

                                                case 3: //Shutdown

                                                        if($facility_id==1)

                                                                $newReference=80001;

                                                        else if($facility_id==2)

                                                                $newReference=90001;

                                                        break;


                                        }

                                }

                        }

                }

                return $newReference;

        }



I’m not getting any error and I don’t think the events are getting attached, as if the script does not exist at all.

Change


 $('#Scaffold_facility_id, #Scaffold_department_id').on('change',function(){

to


 $('#Scaffold_facility_id, #Scaffold_department_id').change(function(e){

I looked at the code so many times and missed this one each time. slaps self

Still no error or any sign of change event.

Sorry if this topic gives you a hard time.

Where are you checking for these errors? What tool do you use to debug your scripts?

Don’t worry about it. I hope we can get this sorted.

Normally errors happens in browser itself (I’m using Chrome) whenever I try to navigate on my project. I don’t use any script debug tool and honestly I don’t know how to use it.

The errors that show up in the browser are PHP errors. JavaScript errors show up in the browser’s console. To view the console in Chrome, click on Shift+Ctrl+j.

I’ve reproduced a similar script on fiddle and it’s working. You can test it there. Without being able to detect where the error occurs in your script, it’s difficult to fix the problem.

Using Chrome JavaScript console, I’ve got this error after selecting Ops & Maint (1) and CUQ (1).




GET http://localhost/scaffold/newReferenceId?departmentId=1&facilityId=1 404 (Not Found)          jquery.js:8434

send                                                                                              jquery.js:8434

jQuery.extend.ajax                                                                                jquery.js:7986

(anonymous function)                                                                                  create:217

jQuery.event.dispatch                                                                             jquery.js:3058

elemData.handle.eventHandle                                                                       jquery.js:2676



So the events are getting attached but the controller action can’t be found. Looking at the URL that the request is being sent to, the name of your web application is missing. In the script, change this:


url: '/scaffold/newReferenceId',

to this:


url: '" . Yii::app()->createUrl('scaffold/newReferenceId') . "',

or if your scaffold controller is within a module, then it should be:


url: '" . Yii::app()->createUrl('<modulename>/scaffold/newReferenceId') . "',

You mentioned being new to PHP and Yii. You didn’t say anything about being new to programming or JQuery so I foolishly assumed you were looking in the console for errors. I think you need to learn the basics of Yii, JQuery, PHP and code debugging before taking on a complex project such as the one you are doing. It will save you a lot of time in the long run.