how to delete an image in actionUpdate

Hi guys, this is my actionUpdate controller




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

		{

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

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


                        // this line checks if theres is an file, if it does, it can be leave blank, else upload new

                        if ( ( is_object($model->image) && get_class( $model->image ) === 'CUploadedFile' ))


			if($model->save()) {

                            if( strlen($model->image) > 0 )

                                $model->image->saveAs(Yii::app()->basePath.'/../uploads/'.$model->image);

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

                        }

		}


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

			'model'=>$model,

		));




how do i add a ‘single’ button to delete the file and remove the data for the image field in actionUpdate?? as well as when deleting the row in actionDelete

It should unlink this file

unlink(Yii::app()->basePath.’/../uploads/’.$model->image);

thanks

========= edit ===================

i solved the actionDelete with the help of this post : http://www.yiiframework.com/forum/index.php/topic/30689-any-onbeforedelete-example/

by using afterDelete().

but how to do it in the update?

I need an delete Image button in the update,

and i have this function in the model




        public function deleteImage()

        { 

            unlink(Yii::app()->basePath.'/../uploads/'.$this->image);

        }



how do i call this function in the update crud by pressing the button?

Hi, as a note, try this nice tool when you need to upload images: http://github.com/valums/file-uploader

Related to your question:

Deleteing the image when delete button is pressed in CGridView:

When del button is pressed, then it calls an action: index.php?r=yourcontroller/delete, the call is made as a Post,




	public function actionDelete($id)

	{

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

		{

			// we only allow deletion via POST request

			try{

				// $this->loadModel($id)->delete();  // ORIGINAL LINE

  

// modify to:


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

                                // then, delete using a function:

                                $this->deleteMyAssociatedImage($model->filenameAndPathOfThatImage);

                       		// or delete directly directly:  

                       		@unlink("yourpath_where_you_store_the_image/".$model->filename);

                       		// then..delete the model:

                              $model->delete();


			}

			catch(CDbException $e){

			}


			// 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.');

	}

Deleting the image in update scenario:

You show a a view that presents your image:

start of your view.php file:


<form>

    <img src='<?php echo $model->getImagePathForView(); ?>'>

    

<div id='actionresponse'></div>


<?php 

echo CHtml::ajaxButton(

	"Delete the Image without leave the form",

	array('mycontroller/deleteImageFromUpdate','id'=>$model->yourmodelid),

	array('success'=>

		'function(data){ jQuery("#actionresponse").html(data) }')

);		

?>


</form>

end of your view.php file:

In your controller, define the action: actionDeleteImageFromUpdate()




public function actionDeleteImageFromUpdate($id){

    

   $model = YourModelClass::model()->findByAttributes(array("id"=>$id));


    $path = "your image path here";

    $filename = $model->imagefilename;


  $fullpath = $path."/".$filename;


   @unlink($fullpath);


  echo "OK";  // this message will appear when ajax call finish.

}



thanks for reply, but not the delete action, just want to delete the file, not the post. and the button is prefered to be located in /update/, as an ajax button.

probably should write an ajax button for this. and call a php function instead of doing the mvc way.

please review again the note i post later, i update it to add the update case.

Oh yea! nice stuff bluyell!!

The following code worked for me:

@model:




protected function afterDelete() {

        parent::afterDelete();

        $rootPath=Yii::app()->getBasePath().'/..';

        unlink($rootPath.'/images/'.$this->image);

    }



Assuming model()->image attribute is the filename and images are stored into $rootPath/images/

Yes it will work if your idea is to delete the database record AND the associated image. The provided example (written by me later) only deletes the image, via ajax, and not the model, this is need only if your idea is to delete the image without deleting the entire model. if your idea is to delete both (record and associated image) then your code is the right way.

As a recomendation, you can hold your entire image in a LONG_BLOB field (using mysql, use the LONG_BLOB), then it can help you in various ways. using this method, is an easy way to provide the image via actions, but if your images are soo large, then you must consider various options, like holding the image as a separated file.

thank you

How can we add the delete button to the image when update action was happened?

do you want to delete image when new file is uploaded?

grt … Itz work for me …

Thnk u so much …

My code is bellow :




public function actionDelete($id)

	{

	


		//$this->loadModel($id)->delete();

		try{

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

        

        unlink(Yii::app()->basePath.'/../images/products/'.$model->product_picture);

		$model->delete();

		}

		 catch(CDbException $e){

                        }


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

			}

	}