Skip to main content

How to upload image(photo), and path entry in database with update functionality

I saw many posts that community newbie is confuse in image/photo upload with random name. so I post this topic covering all useful things regarding to image/photo upload(not covering image attribute related functionality)

View : 

_form.php file:
..
//form options array...
'htmlOptions' => array(
        'enctype' => 'multipart/form-data',
    ),
...
..
//Other elements
..
..
<div class="row">
        <?php echo $form->labelEx($model,'image'); ?>
        <?php echo CHtml::activeFileField($model, 'image'); ?>  // by this we can upload image
        <?php echo $form->error($model,'image'); ?>
</div>
<?php if($model->isNewRecord!='1'){ ?>
<div class="row">
     <?php echo CHtml::image(Yii::app()->request->baseUrl.'/banner/'.$model->image,"image",array("width"=>200)); ?>  // Image shown here if page is update page
</div>
..
..
Other elements
..
..
.. ..

Model : 

just add below line in rules() method in Model
array('image', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'), // this will allow empty field when page is update (remember here i create scenario update)
for all others rules you had to give scenario for insert and update as the rule will apply on both page( Insert and Update ) i.e:
array('title, image', 'length', 'max'=>255, 'on'=>'insert,update'),
.. .. Now comes the main part,

Controller : 

Create controller will upload image with random name and enter required database entry.
public function actionCreate()
    {
        $model=new Banner;  // this is my model related to table
        if(isset($_POST['Banner']))
        {
            $rnd = rand(0,9999);  // generate random number between 0-9999
            $model->attributes=$_POST['Banner'];
 
            $uploadedFile=CUploadedFile::getInstance($model,'image');
            $fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
            $model->image = $fileName;
 
            if($model->save())
            {
                $uploadedFile->saveAs(Yii::app()->basePath.'/../banner/'.$fileName);  // image will uplode to rootDirectory/banner/
                $this->redirect(array('admin'));
            }
        }
        $this->render('create',array(
            'model'=>$model,
        ));
    }
Now comes the update action,
public function actionUpdate($id)
    {
        $model=$this->loadModel($id);
 
        if(isset($_POST['Banner']))
        {
            $_POST['Banner']['image'] = $model->image;
            $model->attributes=$_POST['Banner'];
 
            $uploadedFile=CUploadedFile::getInstance($model,'image');
 
            if($model->save())
            {
                if(!empty($uploadedFile))  // check if uploaded file is set or not
                {
                    $uploadedFile->saveAs(Yii::app()->basePath.'/../banner/'.$model->image);
                }
                $this->redirect(array('admin'));
            }
 
        }
 
        $this->render('update',array(
            'model'=>$model,
        ));
    }
Above example is Upload image in specific folder and enter require entry in database. On update it will overwrite image in folder and update the data.

Popular posts from this blog

Yii, return to previous url after login or logout

If you want to return to your previous url after login or logout try this : <?php $this -> redirect (Yii :: app () -> request -> urlReferrer ); ?> To set the return url to be the url that was before the login page or registeration page was called you can put following code in views/layouts/main.php file : <?php //this checks id the controller action is not 'login' then it keeps the current url in returnUrl if (CController :: getAction () -> id != 'login' ) { Yii :: app () -> user -> setReturnUrl (Yii :: app () -> request -> getUrl ()); } ?>

yii, Executing a SQL without calling a Model

yii, Executing a SQL without calling a Model <? $connection = Yii :: app () -> db ; $sql = "SELECT id,username FROM users" ; $command = $connection -> createCommand ( $sql ); $dataReader = $command -> query (); $rows = $dataReader -> readAll (); print_r ( $rows ); ?>