Update on upload form action?

So I finally got the upload working but I am not sure how to deal with the update action.

Here is my actionCreate


public function actionCreate()

	{

		$model=new Assets;

		

		// Uncomment the following line if AJAX validation is needed

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


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

		{

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

			if($model->save())

			 

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

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

            if($model->save())

            {

            	$file= 'images/'.$model->filename->name;

            	$model->filename->saveAs($file);

                //model->filename->saveAs(Yii::app()->baseUrl.'/images');

                // redirect to success page

            	

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

			}

		}


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

			'model'=>$model,

		));

	}

But the update is different:

its renderpartial


<?php

$this->breadcrumbs=array(

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

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

	'Update',

);


$this->menu=array(

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

	array('label'=>'Create Assets', 'url'=>array('create')),

	array('label'=>'View Assets', 'url'=>array('view', 'id'=>$model->id)),

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

);

?>




<h1>Update Assets <?php echo $model->id; ?></h1>


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

I get the following error:

Please fix the following input errors:

Filename cannot be blank.

on ur model, function rules, add the following code




array('images', 'file', 'types'=>'jpg, gif, png','allowEmpty'=>true, 'on'=>'update'),



Still get the same error

Even though I added this to rules


array('filename', 'file', 'types'=>'jpg, gif, png','allowEmpty'=>true, 'on'=>'update'),

Please fix the following input errors:

Filename cannot be blank.

again my model looks like this:


<?php


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

		);

	}

	

	

	

	

/*  public function actionUpload()

{

        Yii::import("ext.EAjaxUpload.qqFileUploader");

 		$bUrl=Yii::app()->baseUrl.'uploads';

        $folder=$bUrl;

        $allowedExtensions = array("jpg");

		$minSizeLimit=10;

        $sizeLimit = 3 * 1024 * 1024;// maximum file size in bytes

        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);

        $result = $uploader->handleUpload($folder);

        $result=htmlspecialchars(json_encode($result), ENT_NOQUOTES);

        echo $result;// it's array

}*/

  /*

  public function actionUpload() {

      $form = new UploadForm;

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

          if ($form->validate()) {

              $form->filename = CUploadedFile::getInstance($form, 'filename');

              //$file= dirname(Yii::app()->request->scriptFile) . DIRECTORY_SEPARATOR . $form->image->name;

              $file= 'protected/data/'.$form->filename->name;

              $form->filename->saveAs($file);

          }

      }

      $this->render('upload', array('form'=>$form));

  } */

  

	/**

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

				'users'=>array('*'),

			),

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

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

				'users'=>array('@'),

			),

		

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

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

				'users'=>array('@'),

			),

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

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

				'users'=>array('admin'),

			),

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

		

		// Uncomment the following line if AJAX validation is needed

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


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

		{

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

			if($model->save())

			 

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

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

            if($model->save())

            {

            	$file= 'images/'.$model->filename->name;

            	$model->filename->saveAs($file);

                //model->filename->saveAs(Yii::app()->baseUrl.'/images');

                // redirect to success page

            	

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

		{

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

			if($model->save())

				

		{

            	$file= 'images/'.$model->filename->name;

            	$model->filename->saveAs($file);

                //model->filename->saveAs(Yii::app()->baseUrl.'/images');

                // redirect to success page

            	

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

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

			'dataProvider'=>$dataProvider,

                    

		));

                

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new Assets('search');

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

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

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


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

	 */

	public function loadModel($id)

	{

		$model=Assets::model()->findByPk($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']==='assets-form')

		{

			echo CActiveForm::validate($model);

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

		}

	}

}



Also how do you deal with when the file record gets deleted how do you go about deleting the file?

hi,

are u set the filename as required on the rules? if yes, try remove it

in the function actionDelete




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

if (!empty($model->filename))

    unlink(path/to/file);


$model->delete();



Thank you very much.

Good stuff with that I was able to figure out how to get it working.

The only question I have is on update if you change the file then how about deleting the old file on update?

hello,

maybe this will help you




public function actionUpdate($id)

	{

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

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


		// Uncomment the following line if AJAX validation is needed

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


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

		{

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

			if (!empty($_FILES['DItems']['name']['download_file'])) {

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

				// remove current photo		

				if ($old->download_file != "") {

					unlink('images/download/items/'.$old->download_file);

				}		

			} else {

				$model->download_file = $old->download_file;

			}	

			if($model->save()) {

				if (!empty($_FILES['DItems']['name']['download_file'])) {

					$model->download_file->saveAs('images/download/items/'.$model->download_file);

				}

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

			}

		}


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

			'model'=>$model,

		));

	}