Hi All
I am trying to upload image in yii framework using below code.
If i selected a image it upload successfully but when validation error comes image is gone.
At the time of update functionality if image is not selected gives the error.
my view
<?php echo CHtml::image(’/payroll/images/profile_images/’.$model->image_path,’’,array(‘class’=>“profileImage”));
echo $form->fileField($model, 'image_path',array('onchange'=>"uploadProfilePicture(this)"));
echo $form->error($model, 'image_path');
?>
my controller
public function actionCreate()
{
$model=new Users;
$model->gender="1";
$model->under_probation="1";
$model->is_active="1";
$model->image_path="default.png";
$address=new EmployeesAddressDetails;
$user=UserBase::getUserViewRequirements(10);
if(isset($_POST['Users'],$_POST['EmployeesAddressDetails']))
{
$model->attributes=$_POST['Users'];
$model->created_at=date('YmdHis');
$model->created_by=Yii::app()->user->firstName;
$model->id_tenant=Yii::app()->user->idTenant;
$model->image_path=CUploadedFile::getInstance($model,'image_path');
$isExist=UserBase::isUserExist($model->username);
if(!($isExist)){
if($model->save()){
if($model->image_path!=""){
$model->image_path->saveAs(YiiBase::getPathOfAlias('webroot').'/images/profile_images/'.$model->image_path);
}
$address->attributes=$_POST['EmployeesAddressDetails'];
$address->id_user=$model->id;
$address->save();
if(isset($_POST['roles'])){
UserBase::assignRoles($_POST['roles'],$model->id);
}
$this->redirect(array('/basicInfo/index','uid'=>$model->id));
}
}else{
Yii::app()->user->setFlash('error', "User Already Exist Please Try With Different Login Id");
}
}
$this->render('/users/basicInfo/create',array(
'model'=>$model,'address'=>$address,'user'=>$user
));
}
Below is the script to upload a picture
function uploadProfilePicture(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var photo = (e.target || e.srcElement).result;
$('.profileImage').attr('src', photo);
}
reader.readAsDataURL(input.files[0]);
}
}