Image upload problem

Image is not upload on form submission. Although I have set the right rules and htmloptions is also set. In short, form is submitted even if I do not upload the image. Update works absolute fine, but create does not. However, if I remove ‘on’=>‘create’ from rules, then upload works absolutely fine and validation is rightfully done for Create model. But this messes up with update. Please help me with a solution.

Here is the code for model:




<?php


/**

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

 *

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

 * @property integer $ID

 * @property string $image_path

 */

class Pic extends CActiveRecord

{

	/**

	 * Returns the static model of the specified AR class.

	 * @return Pic the static model class

	 */

     public $image_path;

     public $update_image;

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 'tbl_pic';

	}


	/**

	 * @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('image_path', 'file', 'types'=>'jpg, gif, png, jpeg', 'allowEmpty'=>false,'on'=>'create'),

            array('update_image','file','types'=>'jpg, gif, png, jpeg','allowEmpty'=>false,'on'=>'update'),

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

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

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

		);

	}


	/**

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

	 */

	public function attributeLabels()

	{

		return array(

			'ID' => 'ID',

			'image_path' => 'Image',

            'img_path' => 'Image',

            'admin_rate'=>'Image Rating',

            'current_image' => 'Current Image',

            'update_image' => 'Update Image'

		);

	}


	/**

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


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

			'criteria'=>$criteria,

		));

	}

    public function getMaxID()

    {

        $maxid=Yii::app()->db->createCommand()

        ->select('max(ID)')

        ->from('tbl_pic')

        ->queryScalar();

        return $maxid;

    }

}



Here is the controller code




<?php


class PicController 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/column3';

	/**

	 * @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','jrating','jRatingAdmin'),

				'roles'=>array('siteuser'),

			),

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

				'actions'=>array('create','update'),

				'roles'=>array('siteadmin'),

			),            

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

				'actions'=>array('admin','delete'),

				'roles'=>array('siteadmin'),

			),

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


		// Uncomment the following line if AJAX validation is needed

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


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

		{

			$uploadedImage = CUploadedFile::getInstance($model,'image_path');

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

			if($model->validate())

			{

				if (!($uploadedImage===NULL))

				{

				$maxID = Yii::app()->db->createCommand()

				  ->select('max(ID) as max')

				  ->from('tbl_pic')

				  ->queryScalar();

				$TimeCreated=new CDbExpression('NOW()');

				$short_image_name='img_'. ($maxID+1) . '_' . date('YmdHisU') . ".jpg";

				$normal_image_name='beauty_img/normal/' . $short_image_name;

				list($width, $height, $type, $attr) = getimagesize($uploadedImage->getTempName());

				if($height>600)

				{

					$normal_width = $width*600/$height;

					$normal_height = 600;

				}

				else

				{

					$normal_width=$width;

					$normal_height=$height;

				}				

				if($height>150)

				{

					$thumb_width = $width*150/$height;

					$thumb_height = 150;

				}

				else

				{

					$thumb_width=$width;

					$thumb_height=$height;

				}

                

                if($type==2)

                {

                    $largeimage = imagecreatefromjpeg($uploadedImage->getTempName());

                }

                if($type==3)

                {

				    $largeimage = imagecreatefrompng($uploadedImage->getTempName());

                }

                if($type==1)

                {

                    $largeimage = imagecreatefromgif($uploadedImage->getTempName());

                }

                imagefilter($largeimage, IMG_FILTER_GRAYSCALE);

				$normal = imagecreatetruecolor($normal_width, $normal_height);

				$thumb = imagecreatetruecolor($thumb_width, $thumb_height);

				imagecopyresampled($normal, $largeimage, 0, 0, 0, 0,$normal_width, $normal_height, $width, $height);

				imagejpeg($normal, $normal_image_name);

				imagecopyresampled($thumb, $largeimage, 0, 0, 0, 0,$thumb_width, $thumb_height, $width, $height);

				$thumb_image_name='beauty_img/thumb/' . $short_image_name;

				imagejpeg($thumb, $thumb_image_name);

				imagedestroy($largeimage);

				imagedestroy($normal);

				imagedestroy($thumb);

				$model->img_path =  $short_image_name;

				}

				if($model->save(false))

				{

					

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

		{

			$uploadedImage = CUploadedFile::getInstance($model,'update_image');

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

			if($model->validate())

			{

				if (!($uploadedImage===NULL))

				{

					if($model->img_path!=NULL)

					{

						unlink('beauty_img/normal/' . $model->img_path);

						unlink('beauty_img/thumb/' . $model->img_path);

					}

					$TimeCreated=new CDbExpression('NOW()');

					$short_image_name='img_'. $model->ID . '_' . date('YmdHisU') . ".jpg";

					$normal_image_name='beauty_img/normal/' . $short_image_name;

					list($width, $height, $type, $attr) = getimagesize($uploadedImage->getTempName());

					if($height>600)

					{

						$normal_width = $width*600/$height;

						$normal_height = 600;

					}

					else

					{

						$normal_width=$width;

						$normal_height=$height;

					}				

					if($height>150)

					{

						$thumb_width = $width*150/$height;

						$thumb_height = 150;

					}

					else

					{

						$thumb_width=$width;

						$thumb_height=$height;

					}

                    if($type==2)

                    {

                        $largeimage = imagecreatefromjpeg($uploadedImage->getTempName());

                    }

                    if($type==3)

                    {

    				    $largeimage = imagecreatefrompng($uploadedImage->getTempName());

                    }

                    if($type==1)

                    {

                        $largeimage = imagecreatefromgif($uploadedImage->getTempName());

                    }

                    imagefilter($largeimage, IMG_FILTER_GRAYSCALE);

					$normal = imagecreatetruecolor($normal_width, $normal_height);

					$thumb = imagecreatetruecolor($thumb_width, $thumb_height);

					imagecopyresampled($normal, $largeimage, 0, 0, 0, 0,$normal_width, $normal_height, $width, $height);

					imagejpeg($normal, $normal_image_name);

					imagecopyresampled($thumb, $largeimage, 0, 0, 0, 0,$thumb_width, $thumb_height, $width, $height);

					$thumb_image_name='beauty_img/thumb/' . $short_image_name;

					imagejpeg($thumb, $thumb_image_name);

					imagedestroy($largeimage);

					imagedestroy($normal);

					imagedestroy($thumb);

					$model->img_path =  $short_image_name;

				}

				if($model->save(false))

				{

					

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

	{

		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('Pic');

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

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new Pic('search');

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

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

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


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

			'model'=>$model,

		));

	}


    public function actionJRating()

    {

        $aResponse['error'] = false;

        $aResponse['message'] = '';

        

        // ONLY FOR THE DEMO, YOU CAN REMOVE THIS VAR

        	$aResponse['server'] = ''; 

        // END ONLY FOR DEMO

        	

        	

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

        {

        	if(htmlentities($_POST['action'], ENT_QUOTES, 'UTF-8') == 'rating')

        	{

        		/*

        		* vars

        		*/

        		$id = intval($_POST['idBox']);

        		$rate = floatval($_POST['rate']);

        		

        		// YOUR MYSQL REQUEST HERE or other thing <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/smile.gif' class='bbc_emoticon' alt=':)' />

        		/*

        		*

        		*/

        		if(!Yii::app()->user->isGuest && Yii::app()->user->id<>1)

                {

                    $sql="Delete from tbl_beauty WHERE pid=".Yii::app()->user->id." AND picid=".$id.";";

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

                    $command->execute();

                    $sql="Insert into tbl_beauty (pid,rating,picid) VALUES(".Yii::app()->user->id.",".$rate.",".$id.");";

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

                    $command->execute();

  		            // if request successful                    

                    $success=true;

                }

                else

                {

                    // else $success = false;

                    $success=false;

                }


        		

        		

        		

        		// json datas send to the js file

        		if($success)

        		{

        			$aResponse['message'] = 'Your rate has been successfuly recorded. Thanks for your rate <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/smile.gif' class='bbc_emoticon' alt=':)' />';

        			

        			// ONLY FOR THE DEMO, YOU CAN REMOVE THE CODE UNDER

        				$aResponse['server'] = '<strong>Success answer :</strong> Success : Your rate has been recorded. Thanks for your rate <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/smile.gif' class='bbc_emoticon' alt=':)' /><br />';

        				$aResponse['server'] .= '<strong>Rate received :</strong> '.$rate.'<br />';

        				$aResponse['server'] .= '<strong>ID to update :</strong> '.$id;

        			// END ONLY FOR DEMO

        			

        			echo json_encode($aResponse);

        		}

        		else

        		{

        			$aResponse['error'] = true;

        			$aResponse['message'] = 'An error occured during the request. Please retry';

        			

        			// ONLY FOR THE DEMO, YOU CAN REMOVE THE CODE UNDER

        				$aResponse['server'] = '<strong>ERROR :</strong> Your error if the request crash !';

        			// END ONLY FOR DEMO

        			

        			

        			echo json_encode($aResponse);

        		}

        	}

        	else

        	{

        		$aResponse['error'] = true;

        		$aResponse['message'] = '"action" post data not equal to \'rating\'';

        		

        		// ONLY FOR THE DEMO, YOU CAN REMOVE THE CODE UNDER

        			$aResponse['server'] = '<strong>ERROR :</strong> "action" post data not equal to \'rating\'';

        		// END ONLY FOR DEMO

        			

        		

        		echo json_encode($aResponse);

        	}

        }

        else

        {

        	$aResponse['error'] = true;

        	$aResponse['message'] = '$_POST[\'action\'] not found';

        	

        	// ONLY FOR THE DEMO, YOU CAN REMOVE THE CODE UNDER

        		$aResponse['server'] = '<strong>ERROR :</strong> $_POST[\'action\'] not found';

        	// END ONLY FOR DEMO

        	

        	

        	echo json_encode($aResponse);

        }        

    }

    

    public function actionJRatingAdmin()

    {

        $aResponse['error'] = false;

        $aResponse['message'] = '';

        

        // ONLY FOR THE DEMO, YOU CAN REMOVE THIS VAR

        	$aResponse['server'] = ''; 

        // END ONLY FOR DEMO

        	

        	

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

        {

        	if(htmlentities($_POST['action'], ENT_QUOTES, 'UTF-8') == 'rating')

        	{

        		/*

        		* vars

        		*/

        		$img_id = intval($_POST['idBox']);

        		$model->admin_rate = floatval($_POST['rate']);

        		

        		// YOUR MYSQL REQUEST HERE or other thing <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/smile.gif' class='bbc_emoticon' alt=':)' />

        		/*

        		*

        		*/

  		            // if request successful                    

                    $success=true;       		

        		

        		// json datas send to the js file

        		if($success)

        		{

        			$aResponse['message'] = 'Your rate has been successfuly recorded. Thanks for your rate <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/smile.gif' class='bbc_emoticon' alt=':)' />';

        			

        			// ONLY FOR THE DEMO, YOU CAN REMOVE THE CODE UNDER

        				$aResponse['server'] = '<strong>Success answer :</strong> Success : Your rate has been recorded. Thanks for your rate <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/smile.gif' class='bbc_emoticon' alt=':)' /><br />';

        				$aResponse['server'] .= '<strong>Rate received :</strong> '.$rate.'<br />';

        				$aResponse['server'] .= '<strong>ID to update :</strong> '.$id;

        			// END ONLY FOR DEMO

        			

        			echo json_encode($aResponse);

        		}

        		else

        		{

        			$aResponse['error'] = true;

        			$aResponse['message'] = 'An error occured during the request. Please retry';

        			

        			// ONLY FOR THE DEMO, YOU CAN REMOVE THE CODE UNDER

        				$aResponse['server'] = '<strong>ERROR :</strong> Your error if the request crash !';

        			// END ONLY FOR DEMO

        			

        			

        			echo json_encode($aResponse);

        		}

        	}

        	else

        	{

        		$aResponse['error'] = true;

        		$aResponse['message'] = '"action" post data not equal to \'rating\'';

        		

        		// ONLY FOR THE DEMO, YOU CAN REMOVE THE CODE UNDER

        			$aResponse['server'] = '<strong>ERROR :</strong> "action" post data not equal to \'rating\'';

        		// END ONLY FOR DEMO

        			

        		

        		echo json_encode($aResponse);

        	}

        }

        else

        {

        	$aResponse['error'] = true;

        	$aResponse['message'] = '$_POST[\'action\'] not found';

        	

        	// ONLY FOR THE DEMO, YOU CAN REMOVE THE CODE UNDER

        		$aResponse['server'] = '<strong>ERROR :</strong> $_POST[\'action\'] not found';

        	// END ONLY FOR DEMO

        	

        	

        	echo json_encode($aResponse);

        }        

    }    

	/**

	 * 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=Pic::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']==='pic-form')

		{

			echo CActiveForm::validate($model);

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

		}

	}

}



Here is the form:




<div class="form">

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

	'id'=>'pic-form',

	'enableAjaxValidation'=>false,

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

)); ?>

    <?php Yii::app()->clientScript->registerCoreScript("jquery")?>

    <?php  

      $baseUrl = Yii::app()->baseUrl; 

      $cs = Yii::app()->getClientScript();

      $cs->registerScriptFile($baseUrl.'/jquery/jNotify.jquery.js');

      $cs->registerScriptFile($baseUrl.'/jquery/jRating.jquery.js');

      $cs->registerCssFile($baseUrl.'/jquery/jRating.jquery.css');

      $cs->registerCssFile($baseUrl.'/jquery/jNotify.jquery.css');

    ?>

	<script type="text/javascript">

		$(document).ready(function(){

			

			$('.example2').jRating({

				length:5,

				decimalLength:0,

                step:true,

                rateMax:5,

            	  onSuccess : function(){

            	    jSuccess('Success : your rate has been saved <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/smile.gif' class='bbc_emoticon' alt=':)' />',{

            		  HorizontalPosition:'center',

            		  VerticalPosition:'top'

            		});

            	  },

            	  onError : function(){

            	    jError('Error : please retry');

            	  }

			});

			

			$('.example3').jRating({

				length:5,

				decimalLength:0,

                step:true,

                rateMax:5,

            	  onSuccess : function(){

            	    jSuccess('Success : your rate has been saved <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/smile.gif' class='bbc_emoticon' alt=':)' />',{

            		  HorizontalPosition:'center',

            		  VerticalPosition:'top'

            		});

            	  },

            	  onError : function(){

            	    jError('Error : please retry');

            	  }

			});

			

			$('.example4').jRating({

				isDisabled : true,

                rateMax:5

			});

			

			$('.form_img').jRating({

				length:5,

				decimalLength:0,

                step:true,

                rateMax:5,

                phpPath:'<?php echo $this->createUrl('jRatingAdmin')?>',

            	  onSuccess : function(){

            	    jSuccess('Success : your rate has been saved <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/smile.gif' class='bbc_emoticon' alt=':)' />',{

            		  HorizontalPosition:'center',

            		  VerticalPosition:'top'

            		});

            	  },

            	  onError : function(){

            	    jError('Error : please retry');

            	  }

			});

			

			$(".example6").jRating({

				length:5,

				decimalLength:0,

                step:true,

                rateMax:5,

            	  onSuccess : function(){

            	    jSuccess('Success : your rate has been saved <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/smile.gif' class='bbc_emoticon' alt=':)' />',{

            		  HorizontalPosition:'center',

            		  VerticalPosition:'top'

            		});

            	  },

            	  onError : function(){

            	    jError('Error : please retry');

            	  }

			});

		});

	</script>   

    

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


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

	<div class="row">

	<?php if(!$model->isNewRecord && $model->img_path!=NULL)

			{

				echo $form->labelEx($model,'current_image'); 

				echo "<img src=\"beauty_img/thumb/". $model->img_path . "\">";

			}?>

	</div>    

    <div class="row">

		<?php if($model->isNewRecord)

			{

				echo $form->labelEx($model,'image_path');

				//echo CHtml::activeFileField($model,'img_path',array('size'=>60,'maxlength'=>256));


				echo $form->FileField($model,'image_path',array('size'=>60,'maxlength'=>1000));

				echo $form->error($model,'image_path');

			}

			else

			{

				echo $form->labelEx($model,'update_image');

				//echo CHtml::activeFileField($model,'img_path',array('size'=>60,'maxlength'=>256));


				echo $form->FileField($model,'update_image',array('size'=>60,'maxlength'=>1000));

				echo $form->error($model,'update_image');				

			}

        ?>

	</div>

    <div class="row">

        <?php if($model->isNewRecord)

        {

            

            echo "<p class=\"form_img\" data=\"5_".CHtml::encode($model->getMaxID())."\"></p>";

            

        }

        ?>

    </div>

    <div class="row">

        <?php echo $form->hiddenField($model,'img_path'); ?>

        <?php echo $form->hiddenField($model,'admin_rate'); ?>

    </div>

	<div class="row buttons">

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

	</div>


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


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



At first glance your rules looks not ok to me.

For update scenario you declared update_image as not empty but for the create scenario it is image_path.

Shouldn’t it be the same for both?