简体   繁体   中英

Update record without replacing file path in Yii

I have a situation in updating the record without replacing the file path in Yii. Whatever I do, it always empty my file path field in database. here is my code in controller

    if(isset($_POST['Band']))
    {
        $model->attributes = $_POST['Band'];

        $myfile = CUploadedFile::getInstance($model,'logo');

        if($model->save())
        {
            if(!empty($myfile))
            {
                $path = explode(".", $myfile->name);
                $filePath = 'files/'.$myfile->name;
                $myfile->saveAs($filePath);
            }

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

This is what I've done so far but still the logo filed in database updates to null.

Try this code, it's for you -

$model = Band::model()->findbyPK($id);
$model->scenario = 'update';

    if(isset($_POST['Band']) && !empty($_POST['Band']))
     {
       $model->attributes = $_POST['Band'];

         if(empty($_POST['Band']['logo'])) 
            $image = $model->logo;

            $rand = rand(1, 999);
            $myfile = CUploadedFile::getInstance($model,'logo');
            $myfile = "{$rand}-{$myfile}";  //Generate unique file name

            if($model->validate()) {

                if(!empty($myfile)) {
                   $model->logo   = $myfile;
                   $path = explode(".", $myfile->name);
                   $filePath = 'files/'.$myfile->name;

                   if(!$myfile->saveAs($filePath)){ 
                        $model->addError( 'logo', 'File saving error' );
                     }

                  } else {
                          $model->logo = $image;
                        }

                  if( !$model->hasErrors() && $model->save( false ) ) {
                      $this->redirect(array('view','id'=>$model->band_id));
                    }
              }
       }

In model rules array define this -

array('logo', 'file', 'types'=>'jpg, jpeg, bmp, gif, png', 'allowEmpty'=>true, 'on'=>'insert, update')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM