How can i update records without adding same image again?

Hello all. How can i update records without adding same image?If i dont upload image on update its recorded empty in database. All i want to do if file is not uploaded on update then write previous image name which was already in database . Its been 3 days i crawled google but cant find solution. Please Dont write that it has been discussed before.

HERE IS PART OF CODE

model:


public function rules(){

return array(

array('image', 'file', 'types'=>'jpg, gif, png', 'allowEmpty'=>true,'on'=>'insert,update,delete'),..........



controller:


public function actionUpdate($id)

{

$model=$this->loadModel($id);

$modelcat = Cat::model()->findAll();

$oldfilename = $model->image;


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

{

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


if(!empty($uploadedFile)){

if(!empty($model->image)){ // check db if image exists

if(file_exists('newimage/'.$model->image)) { // chech dr if image exists

unlink('newimage/'.$model->image);

}

}

}


if (!empty($uploadedFile)) {


$rnd = rand(0,9999);

$today = date("Ymdhis");

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

$fileName = "{$rnd}{$today}img{$uploadedFile}";

$model->image = $fileName;


} else {


$model=$this->loadModel($id);

$oldfilename = $model->image;


$model->image = $oldfilename;

}


if($model->save())

{


if(!empty($uploadedFile)) // check if uploaded file is set or not

{

$uploadedFile->saveAs('newimage/'.$model->image);

}

$this->render('update',array('model'=>$model,'modelcat'=>$modelcat,));

}

}

It indeed has been discussed before but whatever…

This code is prepared to omit the image field in case it is not uploaded but I don’t know why the file name is overwritten again. It is easier to keep two separated attributes, one for uploaded image instance and another for image name - with only one you have to remember to save the proper value. In your case it should be enough to remove one line:




} else {


$model=$this->loadModel($id);

//$oldfilename = $model->image;


$model->image = $oldfilename;

}



or this "else" part in general.

In controller:




.....

public function actionUpdate($id){

    $model = $this->loadModel($id);

    $oldImage = $model->image;

    if(isset($_POST['ModelName'])){

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

        if(!empty($uploadedFile)){

            .........................

            $oldImage = ...........;

        }

        $_POST['ModelName']['image'] = $oldImage;

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

        .......................

    }

    ...............

}

.....




 $clientimg=$model->image;


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


       

    if(!empty($uploadedFile)){

           if(!empty($model->image)){ // bazada faylin adinin yoxlanmasi

           	if(file_exists('newimage/'.$model->image)) {  // fiziki olaraq faylin yoxlanmasi

		unlink('newimage/'.$model->image);

		          }

              }

          }




		if($model->image===null){

			$fileName = "{$rnd}{$today}img{$uploadedFile}";  // random number + file 

            $model->image = $fileName;

           }else{

	             $model->image=$clientimg;


           }



Thank you Bizley and kjra1707 for you help. i checked little different as above code. and i thought i had problem in model like when creating my model and controller i used crud and there ‘image’ field was in search array. it coused problem i think this might help someone in the future.

With the latest version of the framework (and according to some commits made to the CFileValidator), it looks like you have to set your file attribute to be unsafe. The default behavior at this time is for the attribute’s value to become NULL if the framework could not find an uploaded file. This happens once the validate() method is called and it does not matter whether you have mass assigned values or not because the validator looks for a CUploadedFile instance immediately. Setting the field to be unsafe prevents the validator from force setting the attribute to NULL when validation occurs without an uploaded file. Here’s some test code you can try

MODEL (rules method):




public function rules()

{

    return array(

        // Set file rules and mark as unsafe

        array('file_upload', 'file', 'allowEmpty' => true, 'safe' => false),

    );

}



CONTROLLER:




public function actionUpdate($id)

{

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

    if (isset($_POST['Upload'])) {

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

        $cUploadedFile = CUploadedFile::getInstance($model, 'file_upload');

        if ($cUploadedFile) {

            /**

             * Give your file upload a unique file name here. This won't affect validation because the validator is forced to

             * look directly for a CUploadedFile instance for this attribute if it did not already contain one.

             */

            $model->file_upload = time() . '_' . $cUploadedFile;

        }

        if ($model->save()) {

            if ($cUploadedFile) {

                // Move the uploaded file to its intended target directory, saving it with the unique filename you assigned

                $cUploadedFile->saveAs('uploads/' . $model->file_upload);

            }

            // Redirect here

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

        }

    }

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

        'model' => $model

    ));

}