how to upload file to mysql table using path in yii - php

I try to upload a file to MySQL table and it does not work.
here what i write:
view:
<div class="row">
<?php echo $form->labelEx($model,'doc_ordered_recieved'); ?>
<?php echo $form->fileField($model,'doc_ordered_recieved'); ?>
<?php echo $form->error($model,'doc_ordered_recieved'); ?>
</div>
model:
i add this attribute:
public $doc_ordered_recieved;
and this rulse:
array('doc_ordered_recieved','file','types'=>'pdf', 'allowEmpty'=>true, 'on'=>'update'),
controllers:
public function actionCreate()
{
$model=new Orders;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Orders']))
{
$model->attributes=$_POST['Orders'];
$model->doc_ordered_recieved=CUploadedFile::getInstance($model,'doc_ordered_recieved');
if($model->save())
{
$doc_ordered_recieved->saveAs('http://localhost/files');
$this->redirect(array('view','id'=>$model->oid));
}
}
$this->render('create',array('model'=>$model,
));
}
please help me i don't know why its not work????
thanks you all
eliya

First you need to change the rule to add create scenario:
array('doc_ordered_recieved','file','types'=>'pdf', 'allowEmpty'=>true, 'on'=>'insert,update'),
and in your create action from your controller you need to do this:
public function actionCreate()
{
$model=new Orders;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Orders']))
{
$model->attributes=$_POST['Orders'];
$uploadedFile = CUploadedFile::getInstance($model,'doc_ordered_recieved');
if($model->save())
{
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
if($model->image == null || empty($model->image)){
$rnd = rand(0,9999);// generate random number between 0-9999
$fileName = "{$rnd}-{$uploadedFile}";
$model->image = $fileName;
}
$uploadedFile->saveAs(dirname(__FILE__)..'/files/'. $model->doc_ordered_recieved);
// redirect to success page
}
$this->redirect(array('view','id'=>$model->oid));
}
}
$this->render('create',array('model'=>$model,
));
}

Just by looking at your code I can see that you need to change your file path from
$doc_ordered_recieved->saveAs('http://localhost/files');
to
$doc_ordered_recieved->saveAs(Yii::app()->basePath.'path/to/localFile');
Also, you should provide more information about your model.

Related

Can't update image in yii project

I would like to upload an image and save the image name in database. I can create it and everything is ok, but update has problems. If i update the $model->img (image) value will be blank in db.
This is my model rules:
array('img', 'file','types'=>'jpg, gif, png, jpeg', 'allowEmpty'=>true, 'on'=>'update'),
array('title, img', 'length', 'max'=>255, 'on'=>'insert,update'),
And this is the 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
// $this->performAjaxValidation($model);
if(isset($_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))
{
$uploadedFile->saveAs(Yii::app()->basePath.'/../../images/'.$model->img);
}
}
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
Before the save i check $model->img and it has value.
So i think something wrong with save() in update.
$_POST['News']['img'] = $model->img;
Why you did it? You must remove this line.
$model->attributes=$_POST['News'];
$model->img = $_POST['News']['img'];

How to insert new row in database when i update in yii?

This is my code
can everyone help me please? i want my system insert new record when i update it in yii framework
public function actionUpdate($id)<br/>
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Entrydata']))
{
$_POST['Entrydata']['photo'] = $model->photo;
$model->attributes=$_POST['Entrydata'];
$uploadedFile = CUploadedFile::getInstance($model,'photo');
if($model->save())
{
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
$uploadedFile->saveAs(Yii::app()->basePath.'/../images/'.$model->photo); // image will uplode to rootDirectory/banner/
}
$this->redirect(array('view','id'=>$model->id_entry));
}
}
$this->render('create',array(
'model'=>$model,
));
}
Unset attribute before save.
$model->unsetAttributes(array("id_entry"));
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Entrydata']))
{
$_POST['Entrydata']['photo'] = $model->photo;
$model->attributes=$_POST['Entrydata'];
$uploadedFile = CUploadedFile::getInstance($model,'photo');
// Unset Primary Key value.
$model->unsetAttributes(array("id_entry"));
if($model->save())
{
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
$uploadedFile->saveAs(Yii::app()->basePath.'/../images/'.$model->photo); // image will uplode to rootDirectory/banner/
}
$this->redirect(array('view','id'=>$model->id_entry));
}
}
$this->render('create',array(
'model'=>$model,
));
}

How To Upload A File Using A Model in yii?

i have read this article http://yiiframework.com/wiki/2
and i have done everything step by step .
but it's not working !
this is the model which i just copy and then paste :
class Item extends CActiveRecord
{
public $image;
// ... other attributes
public function rules()
{
return array(
array('image', 'file', 'types'=>'jpg, gif, png'),
);
}
}
my view is exactly the same as the article :
$form = $this->beginWidget(
'CActiveForm',
array(
'id' => 'upload-form',
'enableAjaxValidation' => false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)
);
// ...
echo $form->labelEx($model, 'image');
echo $form->fileField($model, 'image');
echo $form->error($model, 'image');
// ...
echo CHtml::submitButton('Submit');
$this->endWidget();
and my controller is :
class ItemController extends CController
{
public function actionCreate()
{
$model=new Item;
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->save())
{
$model->image->saveAs(dirname(__FILE__).'/a.txt');
// redirect to success page
}
}
$this->render('create', array('model'=>$model));
}
}
when i choose an image(jpg , png , or something else) the controller doesn't see my file , i mean isset($_FILES['Item']) is false ... i know it's false because i check it with var_dump hundreds of times :
public function actionCreate()
{
$model=new Item;
var_dump(isset($_POST['Item']));
...
i also test var_dump(isset($_FILES['Item'])) which was false either .
for every kinds of file(except plain txt file) $_POST['Item']) remains empty.
i checked my request using firebug network panel(both Firefox and chrome) and the request had the file .
i have already check this question , seems it's the same problem but the answers wasn't useful because CUploadedFile::getInstance and CUploadedFile::getInstanceByName are also return null for my case
what do you think ?
The Problem was not related to Yii Framework or my php code because i just test the same code on two different machine and that works just fine .
i am using wamp on my own computer and i guess the problem was something related to Apache or php configurations.
In controller change and use like this:
class ItemController extends CController
{
public function actionCreate()
{
$model=new Item;
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
$uploadedFile = CUploadedFile::getInstance($model,'image');
if($model->save())
{
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
if($model->image == null || empty($model->image)){
$rnd = rand(0,9999);// generate random number between 0-9999
$fileName = "{$rnd}-{$uploadedFile}";
$model->image = $fileName;
}
$uploadedFile->saveAs(dirname(__FILE__)..'/images/'. $model->image);
// redirect to success page
}
}
}
$this->render('create', array('model'=>$model));
}
}

Yii/PHP - How to Create Data Only Once?

everyone. Just like my post, how to create a file only once?
Here's FileController.php
public function actionCreate()
{
$model=new File;
if(isset($_POST['File']))
{
$simpan=$model->nama_file=CUploadedFile::getInstance($model,'nama_file');
if(empty($simpan)){
$model->attributes=$_POST['File'];
$model->save();
}
else{
$model->attributes=$_POST['File'];
$model->pengunggah=Yii::app()->user->id;
$model->nama_file = CUploadedFile::getInstance($model, 'nama_file');
if($model->save()){
$simpan->saveAs(Yii::app()->basePath .
'/../files/' . $model->nama_file.'');
//Yii::app()->user->setFlash('success', "Data berhasil disimpan!");
$this->redirect(array('view','id'=>$model->id_file));
}
}
}
$this->render('create',array(
'model'=>$model,
));
}
After a user create a file, he/she cannot create another, it only allows user to create only once. How to implement it? Thanks a lot

Stay on current page after submit button in YII Framework

I am trying to submit a form , after form submition the current page should stay on with user entered datas . how to achieve this ?
public function actionUpload()
{
$model=new UploadModel();
$basemodel=new BaseContactList();
$importmodel=new ImportedFilesModel();
$importmodel->name =$basemodel->name;
$importmodel->import_date = $now->format('Y-m-d H:i:s');
$importmodel->server_path = $temp;
$importmodel->file_name = $name;
$importmodel->crm_base_contact_id = $crm_base_contact_id;
if ($importmodel->save())
echo "Import saved";
else
echo "Import Not Saved";
unset($_POST['BaseContactList']);
$this->redirect(Yii::app()->request->urlReferrer);
}
This line "$this->redirect(Yii::app()->request->urlReferrer);" goes to previous page but the user entered values are cleared . How to redirect to previous page without clearing the values in the form ??
Same with when you view the error message after failed model saving. Instead of doing redirection, you can just pass the saved model to the form.
public function actionIndex(){
$model = new Model();
if (isset($_POST[get_class($model)]){
$model->setAttributes($_POST[get_class($model)]);
if ($model->save()){
//do nothing
//usually people do a redirection here `$this->redirect('index');`
//or you can save a flash message
Yii::app()->user->setFlash('message', 'Successfully save form');
} else {
Yii::app()->user->setFlash('message', 'Failed to save form');
}
}
//this will pass the model posted by the form to the view,
//regardless whether the save is successful or not.
$this->render('index', array('model' => $model));
}
In the index view you can do something like.
<?php if (Yii::app()->user->hasFlash('message')):?>
<div class="message"><?php echo Yii::app()->user->getFlash('message');?></div>
<?php endif;?>
<?php echo CHtml::beginForm();?>
<!-- show the form with $model here --->
<?php echo CHtml::endForm();?>
The downside is, when you accidentally hit Refresh button (F5), it will try to post the form again.
Or you can save it using user session using setFlash.
public function actionUpload()
{
$model=new UploadModel();
$basemodel=new BaseContactList();
$importmodel=new ImportedFilesModel();
$importmodel->name =$basemodel->name;
$importmodel->import_date = $now->format('Y-m-d H:i:s');
$importmodel->server_path = $temp;
$importmodel->file_name = $name;
$importmodel->crm_base_contact_id = $crm_base_contact_id;
if ($importmodel->save())
echo "Import saved";
else
echo "Import Not Saved";
unset($_POST['BaseContactList']);
//here we go
Yii::app()->user->setFlash('form', serialize($basemodel));
//
$this->redirect(Yii::app()->request->urlReferrer);
}
In the previous form, you load the value from the session.
public function actionForm(){
if (Yii::app()->user->hasFlash('form')){
$basemodel = unserialize(Yii::app()->user->getFlash('form');
} else {
$basemodel = new BaseContactList();
}
$this->render('form', array('basemodel' => $basemodel));
}
I do not know whether really such a long code is needed to do such a thing but I can simply do it by this.
Suppose i have an actionUpdate
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Products']))
{
$model->attributes=$_POST['Products'];
$model->save();
// remove this redirect() line
// $this->redirect(array('view', 'id' => $model->productId));
}
$this->render('update',array(
'model'=>$model,
));
}
If in your action, you are redirecting after saving your data then just remove that line and you are done, provided that you are rendering the form again in the following lines
If you are not rendering the form in the next lines then you can do it yourself like
if($model->save())
{
$this->render('update',array(
'model'=>$model,
));
Yii::app()->end();
}
Will this do?
if ($importmodel->save())
$_SERVER['PHP_SELF'];
Simple Redirect to the same action and send the model loaded as an arguement

Categories