upload file in Yii not showing image name/path - php

im here again with a new problem. I am trying to upload a file using yii upload function.
Everything saves well, exept for the image. Here's my code:
Controller:
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$dir = Yii::getPathOfAlias('webroot.images.producten');
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Producten']))
{
$model->attributes=$_POST['Producten'];
$model->images=CUploadedFile::getInstance($model,'images');
$nf = $model->images;
if($model->save()){
$this->redirect(array('view','id'=>$model->id));
$model->images->saveAs($dir.'/'.$nf);
$model->images = $nf;
$model->save();
}
}
$this->render('update',array(
'model'=>$model,
));
}
Form:
<div class="row">
<?php echo $form->labelEx($model,'images'); ?>
<?php echo CHtml::activeFileField($model,'images'); ?>
<?php echo $form->error($model,'images'); ?>
</div>
Model:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('naam, beschrijving, prijs', 'required'),
array('images,', 'file', 'allowEmpty'=>true,
'safe' => true,
'types'=> 'jpg, jpeg, png, gif',
'maxSize' => (1024 * 300), // 300 Kb
),
array('aangepast_door', 'numerical', 'integerOnly'=>true),
array('naam', 'length', 'max'=>50),
array('prijs, actieprijs', 'length', 'max'=>10),
//array('toegevoegd, aangepast', 'safe'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('naam, beschrijving, prijs, actieprijs', 'safe', 'on'=>'search'),
);
}
Please help me get this to work.

First of all add enctype= "multipart/form-data" to your form tag or add "enctype" option to associative array if you used form widget yo begin form.
If it will not helps you, please post var_dump($_POST) results here

Related

Yii 1.x - required field saves empty

I have a field set as required in the model, yet I have seen users saving it as an empty string (ie. ''). When I tested it, I do receive the "Cannot be blank" message properly, so don't know how to prevent this in the future. Do I have to specify all scenarios in the rule (eg, 'insert', 'update')? By the way, I tried updating the field, and it doesn't let me save it empty (I even tries spaces).
These are the rules applied on the field (model):
public function rules()
{
return array(
array('field', 'required'),
array('field', 'length', 'max'=>4096),
array('field', 'safe', 'on'=>'search'),
);
}
For #RiggsFolly :) the controller action:
public function actionUpdate($id)
{
$model = Model::model()->findByPk($id);
$formData = Yii::app()->request->getPost('Model');
if ($formData)
{
$model->attributes = $formData;
$model->save();
}
$this->render('update',array(
'model'=>$model
));
}
... and the view:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'form'
)); ?>
<?php echo $form->textArea($model,'text',array( 'rows'=>5 ')); ?>
<?php $this->endWidget(); ?>
Can you imagine any scenario this field could be saving an empty string in the database?

Yii PHP file uploader overwriting on update

I have a basic form in PHP framework Yii, the action to create works fine, however, when i update the record (for example if i'm not changing the file upload, but another field), it overwrites the file upload and blanks it, can anyone assist me? I've tried all the validation I can think of around the controller items, but no matter what i add it still blanks it on update.
Here's the view code
<?php $form=$this->beginWidget('booster.widgets.TbActiveForm', array(
'id'=>'company-form',
'enableAjaxValidation'=>false,
'method' => 'post',
'type' => 'horizontal',
'htmlOptions' => array(
'enctype' => 'multipart/form-data'
)
));
echo $form->textFieldGroup($model,'name',array('class'=>'col-md-5','maxlength'=>75));
echo $form->fileFieldGroup($model, 'logo',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-md-9',
),
'hint' => 'You can only upload jpg, png, gif\'s – max upload filesize is 1.5mb. Square images are advised.<br/>In certain browsers, you can also drag \' drop files into the dropzone.',
)
);
if($model->isNewRecord!='1'){ ?>
<div class="row">
<label class="col-md-3 control-label" style="padding-top: 25px;">Company image</label>
<div class="col-md-6">
<?php echo CHtml::image(Yii::app()->request->baseUrl.'/images/portraits/company/'.$model->logo,"logo",array("class"=>"img-polaroid placeholder")); ?>
</div>
</div>
<?php } ?>
And this is my actionUpdate function in Controller
public function actionUpdate($id)
{
$model=$this->loadModel($id);
if(isset($_POST['Company']))
{
$model->attributes=$_POST['Company'];
$uploadedFile=CUploadedFile::getInstance($model,'logo');
if (is_object($uploadedFile) && get_class($uploadedFile)==='CUploadedFile'){
if(!$uploadedFile == null){
$rnd = rand(0,9999);
$filename_preg1 = preg_replace("/[^a-zA-Z0-9.]/", '', "{$uploadedFile}");
$fileName = "{$rnd}-{$filename_preg1}";
$company = $model->name;
$model->logo = $fileName;
}
if($model->save()){
if(!empty($uploadedFile)){
$fullPath = Yii::app()->basePath . '/../images/portraits/company/' . $fileName;
$uploadedFile->saveAs($fullPath);
}
$this->redirect(array('view','id'=>$model->company_id));
}
}
if($model->save()){
$this->redirect(array('view','id'=>$model->company_id));
}
}
$this->render('update',array(
'model'=>$model,
));
}
Can anyone see where i'm going wrong?
UPDATE
Thanks SiZE, the code you gave me worked in one form and not in the other, the one it didn't work in has validation in the model rules
array('logo', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'),
This only works with the allowEmpty param here as it's not a required field, however, with the rule in place in the model, it still blanks the file field regardless, anyone have any more thoughts?
CActiveForm calls CHtml::activeFileField method wich generates empty hidden field to correctly work with model's rules.
You can try this:
$model=$this->loadModel($id);
$original_logo = $model->logo;
if(isset($_POST['Company'])) {
$model->attributes = $_POST['Company'];
$logo = CUploadedFile::getInstance($model, 'logo');
$model->logo = $logo !== null ? $logo->getName() : $original_logo;
if ($model->save()) {
if ($logo !== null) {
$logo->saveAs(/* specify path with file name here */);
}
$this->redirect(array('view','id'=>$model->company_id));
}
}

Yii Framework store/save submitted file to images folder

Hi, for the past 2 days i've been reading and reading lots of tutorials about saving files to folders in Yii, and neither of them have worked so far. I have the folowing form:
<div class="form">
<?php $form = $this->beginWidget('CActiveForm', array(
'htmlOptions' => array('enctype' => 'multipart/form-data')
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'Binaryfile'); ?>
<?php echo $form->fileField($model,'uploadedFile'); ?>
<?php echo $form->error($model,'uploadedFile'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
endWidget(); ?>
The file field submits the code to a BLOB field in mysql database.
The Controller is as follows:
public function actionCreate()
{
$model=new Estudos;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Estudos']))
{
$model->attributes=$_POST['Estudos'];
$model->binaryfile = CUploadedFile::getInstance($model,'binaryfile'); // grava na bd no campo binaryfile
// $model->binaryfile->saveAs(Yii::app()->params['uploadPath']);
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
And the Model is this one:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('fileName', 'length', 'max'=>100),
array('fileType', 'length', 'max'=>50),
array('binaryfile', 'safe'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, fileName, fileType, binaryfile', 'safe', 'on'=>'search'),
);
}
public $uploadedFile;
// Gravar imagem na base de dados - cria blob field
public function beforeSave()
{
if ($file = CUploadedFile::getInstance($this, 'uploadedFile'))
{
$this->fileName = $file->name;
$this->fileType = $file->type;
$this->binaryfile = file_get_contents($file->tempName);
}
return parent::beforeSave();
}
The code works fine to store a file as a BLOB field, but i need to change the code to store the file in images folder and next to display links that permits to open the file (pdf file) in any browser.
To store the file in images folder i tryed saveAs() in my controller actionCreate but Yii freezes and the webpage becames blank with no error, just blank.
**Anyone can help me... I need this very very much. Many thanks in advance. **
check this link,,in this link say how do it...
http://www.yiiframework.com/wiki/2/how-to-upload-a-file-using-a-model/
Finally i've figured it by myself. The answer was rather simple, but took me 4 days to write it.
In my actionCreate() i did:
public function actionCreate()
{
$model=new Estudos;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Estudos']))
{
$model->attributes=$_POST['Estudos'];
$model->uploadedFile=CUploadedFile::getInstance($model,'uploadedFile');
if($model->save())
$model->uploadedFile->saveAs("pdfs/".$model->uploadedFile,true);
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
**That way the saveAs() function worked like a charm and now saves my submited files in the pdfs folder.
The next step is to try and figure out how to create links for all files submitted to pdfs folder.
Maybe with a foreach() loop.
Best regards...**

Yii model rules "Failed to set unsafe attribute"

I've looking but can't get It to work.
These are my rules in model Acta.php
public function rules()
{
return array(
array('dominio', 'required'),
array('numero, velocidad, grupo, dni, cuit, plan_pago_id', 'numerical', 'integerOnly'=>true),
array('foto, observaciones, situacion, infractor, dominio, tipo_vehiculo, marca, modelo, domicilio, codigo_postal, localidad, provincia, tipo_multa, usuario', 'length', 'max'=>255),
array('hora', 'length', 'max'=>11),
//Here is the problem with only this three attributes
array('municipio, cinemometro, fecha_labrada', 'safe', 'on'=> 'create,update'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, numero, fecha_labrada, velocidad, grupo, foto, observaciones, situacion, infractor, dominio, dni, cuit, tipo_vehiculo, marca, modelo, domicilio, codigo_postal, localidad, provincia, tipo_multa, hora, usuario, plan_pago_id', 'safe', 'on'=>'search'),
);
}
And this is the code on controller ActaController.php
public function actionCreate()
{
$model = new Acta;
if(isset($_POST['Acta']))
{
...
code setting data on $_POST['Acta']
...
$model->attributes = $_POST['Acta'];
$model->save();
}
$this->redirect(array('ingresar'));
}
I can't see the problem. Should be working right?
EDIT:
I thought that the scenario was set automatically. I was wrong.
To fix this the scenario must be set before the attributes:
...
$model->setScenario('create');
$model->attributes = $_POST['Acta'];
...
Before you save, You absolutely have some errors. To be aware about errors do like below:
if($model->validate()){
//NO ERRORS, SO WE PERFORM SAVE PROCESS
$model->save()
}else{
//TO SEE WHAT ERROR YOU HAVE
CVarDumper::dump($model->getErrors(),56789,true);
Yii::app()->end();
//an alternative way is to show attribute errors in view
}
On the other hand, it seems you set some attributes as safe on specific scenarios. But you did not set the scenario.
to set scenario, do like below:
$model->setScenario('THE SCENARIO NAME');
Or:
$model=new YOURMODELNAME('SCENARIO NAME');
I hope it help

Yii Captcha error

I am working in Yii and I am just a beginner and trying my best to learn the framework and here is where I am stuck at :
I have created a user model and the required forms that go with it, and I am trying to implement the Captcha for it :
This is my validation rules in the user model :
$public verifyCode
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('username, password, email', 'required'),
array('username','unique'),
array('email','email'),
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
array('username, password', 'length', 'max'=>45),
array('email', 'length', 'max'=>100),
array('active', 'length', 'max'=>1),
array('created_on, updated_on', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, username, password, email, created_on, updated_on, active', 'safe', 'on'=>'search'),
);
}
And this is my overriden action() in my userController :
public function actions(){
return array(
'captcha'=>array(
'class' => 'CCaptchaAction',
)
);
}
And this is my view file :
<?php if(CCaptcha::checkRequirements()): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
</div>
<div class="hint">Please enter the letters as they are shown in the image above.
<br/>Letters are not case-sensitive.</div>
<?php echo $form->error($model,'verifyCode'); ?>
</div>
<?php endif; ?>
According to me, I think that I am doing everything correctly however, the captcha image is not getting generated. Oh and yes the GD library is installed and if I navigate to the site/contact, there the captcha is generated fine.
I dont seem to understand, where am i getting it wrong.
This is the thing that I see :
The forms seems to be working fine however, I cant see the the captcha image.
Any help would be appreciated.
Regards,
I got the answer, it is because of the access rules that are defined in the controller, I had to modify the controller accessControl like so :
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view','captcha'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform every action
'actions'=>array('create','update','admin','delete'),
'users'=>array('#'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}

Categories