Yii Framework Forum: Update Image - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Update Image Rate Topic: ***** 1 Votes

#1 User is offline   s0mk3t 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 47
  • Joined: 05-May 11
  • Location:Alicante - España(Spain)

Posted 27 May 2011 - 02:36 AM

Hi again to everyone =), i have a new problem with uploading image, i can upload the image with create action, but my problem is when i want update, i wanna can update my db table without new image, but ever say me image cannot be blank, i dont have the image field required...
Model code:
/**
	 * @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('dni, nom, cognoms, adresa, data_naiximent, telefon_1, correu_electronic, lloc_naiximent, poblacio', 'required'),
			array('foto', 'unsafe'),
			array('foto', 'file', 'types'=>'jpg, gif, png'),
			array('dni', 'ext.MyValidators.dniValidate'),
			//.......
		);
	}

Controller code (update)
public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Persona']))
		{
			$model->foto=CUploadedFile::getInstance($model,'foto');
			$name = 'images/personas/'.md5(time()).'_'.$this->normalizar_nombre($model->foto);
			$foto_ = $model->foto;			
			$model->attributes=$_POST['Persona'];
			$model->foto = $name;
			if($model->save())
			{				
				$foto_->saveAs($name);				
				$this->redirect(array('view','id'=>$model->id));
			}
		}

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

I tried with this comment in this wiki http://www.yiiframework.com/wiki/2/ but it give me the same error

Quote

The example above is great, but if you are working with a CRUD interface, then there is a need for a "UPDATE" action. If you update fields but dont upload any files the previous files will be "reset" (made empty) in the model. To prevent this you need to extend the code above.

This approach is based on the explanation from tri, see forum topic >>
http://www.yiiframew...dpost__p__27940

My example:

MODEL:
public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
...
            array('image', 'unsafe'),
...
}

By making the image unsafe the input values for the image field wont be set by $model->attributes=$_POST['Events'];

This allows us to use CUploadedFile data object to set the image data.

CONTROLLER:
/**
     * 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['Events']))
        {
            $model->attributes=$_POST['Events'];
 
            $file_image = CUploadedFile::getInstance($model,'image');
 
            if ( (is_object($file_flyer) && get_class($file_flyer)==='CUploadedFile'))
                $model->flyer = $file_flyer;
 
            if($model->save())
            {
                if (is_object($file_flyer))
                    $model->flyer->saveAs(Yii::app()->basePath.'/../files/flyers/'.$model->flyer);
 
 
                //$this->redirect(array('update','id'=>$model->id));
 
            }
        }
 
        $this->render('update',array(
            'model'=>$model,
        ));
    }


The first "if" check if the upload object is being loaded and filled with the uploaded file. If this is the case then the model->image gets an update otherwise the previous uploaded file remains.

The second "if" in the save will actually save the file on the webserver.

Hope this helps for those who are struggling with the file upload



Grettings and thanks,
s0mk3t

0

#2 User is offline   Maurizio Domba Cerin 

  • Yii - Yesss It Is !!!
  • Yii
  • Group: Yii Dev Team
  • Posts: 4,378
  • Joined: 12-October 09
  • Location:Croatia

Posted 27 May 2011 - 03:49 AM

you need to use scenarios so that you say on create the image is required... but on update it can be empty...

here is my image rules... just adapt them for your case...
...
array('name', 'file', 'types'=>'pdf,txt','on'=>'insert'),
array('name', 'file', 'allowEmpty'=>true,'types'=>'pdf,txt','on'=>'update'),
...

Find more about me.... btw. Do you know your WAN IP?
3

#3 User is offline   s0mk3t 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 47
  • Joined: 05-May 11
  • Location:Alicante - España(Spain)

Posted 27 May 2011 - 05:18 AM

View Postmdomba, on 27 May 2011 - 03:49 AM, said:

you need to use scenarios so that you say on create the image is required... but on update it can be empty...

here is my image rules... just adapt them for your case...
...
array('name', 'file', 'types'=>'pdf,txt','on'=>'insert'),
array('name', 'file', 'allowEmpty'=>true,'types'=>'pdf,txt','on'=>'update'),
...


It work good, a lot of thanks!!
0

#4 User is offline   Vedran 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 13
  • Joined: 02-June 11
  • Location:Sarajevo

Posted 04 June 2011 - 06:35 PM

Hello everyone, :D
I also have a problem with form and uploading image.

What i need to make:

form with approximately 10 fields connected with db, of course. Typical CRUD scenario.One of that fields is "fileField" type, so I can upload image to server and write image name to database, so I could use it later. Form must allow option that in certain cases I will not upload image.

I followed these instructions: How to upload a file using a model

Everything is fine when I include that image, but the form is misbehaving when I don't upload picture, whether I create or update. Instead of saving informations to db, it just rejects all informations from fields and does not update informations in database.
Something like "Cancel" button ::) but there is only "Save" button and it did not save.
I've read all the articles on this forum and on the Internet that talk about similar problems but did not managed to find a solution.


Here is my code.

Model:

Quote

array('banner', 'file', 'types'=>'jpg, gif, png'),


Controller:

Quote

/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Content;

// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);

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


$model->attributes=$_POST['Content'];
$model->banner=CUploadedFile::getInstance($model,'banner');
if($model->save())
$model->banner->saveAs(images/banner/'.$model->banner->name');
$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['Content']))
{
$model->attributes=$_POST['Content'];
$model->banner=CUploadedFile::getInstance($model,'banner');
if($model->save())
$model->banner->saveAs('images/banner/'.$model->banner->name);
$this->redirect(array('view','id'=>$model->id));
}

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


and view (_form):

Quote

<?php echo CHtml::form('', 'post', array('enctype'=>'multipart/form-data')); ?>

...

<?php echo "<b>Banner</b>"?>
<?php echo $form->fileField($model,'banner'); ?>
<?php echo $form->error($model,'banner'); ?>

...

<?php echo CHtml::endForm(); ?>


I really don't know what is wrong in my code and this problem is really bothering me... :unsure:
0

#5 User is offline   Maurizio Domba Cerin 

  • Yii - Yesss It Is !!!
  • Yii
  • Group: Yii Dev Team
  • Posts: 4,378
  • Joined: 12-October 09
  • Location:Croatia

Posted 05 June 2011 - 03:44 AM

Your validation do not pass.. that's why nothing is saved...

you need to allow empty field for the file upload - http://www.yiiframew...lowEmpty-detail
Find more about me.... btw. Do you know your WAN IP?
1

#6 User is offline   Vedran 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 13
  • Joined: 02-June 11
  • Location:Sarajevo

Posted 09 June 2011 - 01:09 PM

View Postmdomba, on 05 June 2011 - 03:44 AM, said:

Your validation do not pass.. that's why nothing is saved...

you need to allow empty field for the file upload - http://www.yiiframew...lowEmpty-detail


Thaaaaaaaaaank you very much!!!!
You saved my life :lol:

Or shuld I say, hvala puno! ;-)
0

#7 User is offline   Vikash Yadav 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 7
  • Joined: 03-May 14

Posted 22 May 2014 - 09:23 AM

great Work Dear You Made my day
very very Thanks.

View Posts0mk3t, on 27 May 2011 - 02:36 AM, said:

Hi again to everyone =), i have a new problem with uploading image, i can upload the image with create action, but my problem is when i want update, i wanna can update my db table without new image, but ever say me image cannot be blank, i dont have the image field required...
Model code:
/**
	 * @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('dni, nom, cognoms, adresa, data_naiximent, telefon_1, correu_electronic, lloc_naiximent, poblacio', 'required'),
			array('foto', 'unsafe'),
			array('foto', 'file', 'types'=>'jpg, gif, png'),
			array('dni', 'ext.MyValidators.dniValidate'),
			//.......
		);
	}

Controller code (update)
public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Persona']))
		{
			$model->foto=CUploadedFile::getInstance($model,'foto');
			$name = 'images/personas/'.md5(time()).'_'.$this->normalizar_nombre($model->foto);
			$foto_ = $model->foto;			
			$model->attributes=$_POST['Persona'];
			$model->foto = $name;
			if($model->save())
			{				
				$foto_->saveAs($name);				
				$this->redirect(array('view','id'=>$model->id));
			}
		}

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

I tried with this comment in this wiki http://www.yiiframework.com/wiki/2/ but it give me the same error


Grettings and thanks,
s0mk3t


0

#8 User is offline   Siki 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 2
  • Joined: 13-March 15

Posted 13 March 2015 - 09:23 PM

Hello!
I have a problem with image name update.
If i update the article which has image, the image name will be blank in database.
this is my controller:
public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$_SESSION['KCFINDER']['disabled'] = false;
                $_SESSION['KCFINDER']['uploadURL'] = Yii::app()->baseUrl."/../images/"; // URL for the uploads folder
                $_SESSION['KCFINDER']['uploadDir'] = Yii::app()->basePath."/../../images/"; // path to the uploads folder
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
                $image_new = $model->img;
		if(isset($_POST['News']))
		{
			//$model->attributes=$_POST['News'];
                        $_POST['News']['img'] = $model->img;
                        $model->attributes=$_POST['News'];
//                        $model->img = $_POST['News']['img'];
                        $uploadedFile=CUploadedFile::getInstance($model,'img');
                        
			if($model->save()){
                                if(!empty($uploadedFile))  // check if uploaded file is set or not
                                {
                                        $uploadedFile->saveAs(Yii::app()->basePath.'/../../images/'.$model->img);
                                }
                                
                               // $model->isNewRecord;
                                
				$this->redirect(array('view','id'=>$model->id));
                        }
		}

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

And this is my model:
	public function rules()
	{
		return array(
			array('title, content, create_at, lang, active', 'required'),
			array('active', 'numerical', 'integerOnly'=>true),
			array('title, intro, img, meta_keys, meta_desc', 'length', 'max'=>255),
			array('lang', 'length', 'max'=>5),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, title, intro, img, content, create_at, lang, active, meta_keys, meta_desc', 'safe', 'on'=>'search'),
                        array('img', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'),
                        array('title, img', 'length', 'max'=>255, 'on'=>'insert,update'),

		);
	}


It works in create action, however if i am update the article, $model->img will be NULL.
Pls help me i dont have idea.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users