Yii2. Error while upload file - php

My Code related is the following:
Model Rules
[['documentTypeId', 'itemId', 'name', 'document'], 'required'],
[['document'], 'file', 'skipOnEmpty' => false, 'extensions' => ['png', 'jpg', 'doc', 'pdf'], 'checkExtensionByMimeType'=>false],
Model method
public function upload($file)
{
if ($this->validate()) {
$userFolder = Yii::getAlias("#app")."/uploads/".$this->item->userId;
if(BaseFileHelper::createDirectory($userFolder) !== false) {
$fileName = uniqid(rand(), false) . '.' . $this->document->extension;
$file->saveAs($userFolder.'/' . $fileName);
$this->document = $file->name;
return true;
} else {
return false;
}
} else {
return false;
}
}
Controller
$model = new ItemDocument();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$file = UploadedFile::getInstance($model, 'document');
if($model->upload($file) !== false) {
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
This is giving me a validation error: "Document can not be blank". If I set "Document" field as not required and submit form I get "Please upload a file."
I am uploading this through a form with some other fields.
Any ideas?

I have found the error it was the model->validate() on controller. When i do:
$model->load(Yii::$app->request->post())
File content is not loaded to the "document" field. Yii generates a hidden field which is empty. So I need first to do this:
$file = UploadedFile::getInstance($model, 'document');
So now my controller looks like this:
$model = new ItemDocument();
if ($model->load(Yii::$app->request->post())) {
$model->document = UploadedFile::getInstance($model, 'document');
if($model->validate()) {
if ($model->upload() !== false) {
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('create', [
'model' => $model,
]);
And I removed the validation inside upload method on model. Hope it helps someone.

Related

how to validate a specific field in yii2

I need to do some stuff before saving my data in DB.
the problem is that the data changes during the validation and save process.
here is some code:
public function actionCreate()
{
$model = new Customers();
if ($model->load(Yii::$app->request->post()) && $model->validate('special_field')) {
// do some stuff
// data changes here
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}
but $model->validate('special_field') function does not work
I've tried this and it worked properly
if ($model->load(Yii::$app->request->post())) {
// your stuff
if ($model->validate('special_field')) {
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
$errors = $model->errors;
var_dump($errors);
die();
}
}

Upload files with different attributes in Yii2 ActiveForm

I have a Yii2 ActiveForm with two form field that accepts file input.
<?= $form->field($model, 'mainImage')->fileInput() ?>
<?= $form->field($model, 'productImage[]')->fileInput() ?>
In the controller i have:
public function actionCreate()
{
$model = new Product();
$model->supplier_id = Yii::$app->user->identity->id;
$imageArray = ['mainImage','productImage'];
$mainImageIndex = 1;
if ($model->load(Yii::$app->request->post())) {
$model->mainImage = UploadedFile::getInstance($model, 'mainImage');
$model->images = $model->singleImageUpload();
//UploadedFile::reset();
// var_dump($model->mainImage);
// exit();
$model->productImage = UploadedFile::getInstances($model, 'productImage');
$images = $model->multipleImageUpload();
$imageCount = count($images);
if ($model->validate() && $model->save(false)) {
for ($i=0; $i < $imageCount; $i++) {
$imageModel = new ProductImage();
$imageModel->product_id = $model->id;
$imageModel->image = $images[$i];
$imageModel->save();
}
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('create', [
'model' => $model,
]);
}
In the Model class, I have these validations rules:
[['mainImage','productImage'], 'safe'],
[['mainImage','productImage'], 'file','skipOnEmpty' => true, 'extensions' => 'jpeg, jpg, png','checkExtensionByMimeType'=>false, 'maxFiles'=>10],
Every time i submit the form I get an error of mainImage field stating Please upload a file. There is no error for productImage
What could be the possible fix for this?
Edit
Images for mainImageand productImage are successfully uploaded though the validation error persists on for the mainImage
The problem was validation in the model class.
I had marked them as safe
[['mainImage','productImage'], 'safe'],
I commented out this validation and it worked
If you want to upload multiple files then you needed to change your view
<?= $form->field($model, 'mainImage')->fileInput() ?>
<?= $form->field($model, 'productImage[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
And your rule in model says that you have been trying to upload multiple image for attributes productImage[] and mainImage. But view says that attribute mainImage used for single file so change the rule.
[['mainImage'], 'file', 'skipOnEmpty' => true, 'extensions' => 'jpeg, jpg, png'],
[['productImage'], 'file','skipOnEmpty' => true, 'extensions' => 'jpeg, jpg, png','checkExtensionByMimeType'=>false, 'maxFiles'=>10],
In controller,
$model->productImage = UploadedFile::getInstances($model, 'productImage');
$model->mainImage = UploadedFile::getInstance($model, 'mainImage');
if ($model->multipleImageUpload()) {
// file is uploaded successfully
return;
}
In your model,
public function multipleImageUpload()
{
if ($this->validate()) {
foreach ($this->imageFiles as $file) {
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
}
return true;
} else {
return false;
}
}
For more reference please go through this link: https://www.yiiframework.com/doc/guide/2.0/en/input-file-upload

Yii2 Blank page while upload file with .php extension

I have a problem when uploading a file with a .php file extension. The problem is becoming blank pages and unsuccessfully redirected to index (files uploaded but the page is blank)
This does not happen when I use other extension files (jpeg, jpg, txt, doc, docx etc).
Ps. I am using Oracle as database and using yii2 UploadedFile
Here my model
public static function tableName()
{
return 'JOB';
}
public function rules()
{
return [
[['JOBNAME', 'CLASS', 'ACTION', 'SCHEDULE', 'STATUS'], 'required'],
[['ID', 'STATUS'], 'integer'],
[['JOBNAME'], 'string', 'max' => 30],
[['FILECOMMAND'], 'file', 'skipOnEmpty' => false, 'extensions' => 'jpeg, php, txt'],
[['CLASS', 'ACTION', 'SCHEDULE'], 'string', 'max' => 100],
[['ID'], 'unique'],
];
}
}
Here my controller
public function actionCreate()
{
$scheduleList = yii::$app->params['cronparam'];
$model = new JOB();
if (yii::$app->request->post()) {
$state = true;
$data = yii::$app->request->post()['JOB'];
try {
$transaction = Yii::$app->db->beginTransaction();
$model->JOBNAME = $data['JOBNAME'];
$model->CLASS = $data['CLASS'];
$model->ACTION = $data['ACTION'];
$model->SCHEDULE = $data['SCHEDULE'];
$model->STATUS = $data['STATUS'];
$model->files = UploadedFile::getInstance($model, 'FILECOMMAND');
$model->FILECOMMAND = $model->files;
$model->files->saveAs(yii::getAlias('#app') . yii::$app->params['pathJobFile'] . $model->files->baseName . '.' . $model->files->extension, false);
if (!$model->save()) {
$ErrorMessage = $model->getErrorMessage($model->getErrors());
throw new Exception($ErrorMessage);
}
$message = "Success insert Job " . ucwords($model->JOBNAME);
$transaction->commit();
} catch (Exception $e) {
$message = $e->getMessage();
$state = false;
$transaction->rollBack();
}
if ($state) {
Yii::$app->session->setFlash('SuccessJob', $message);
$this->redirect('index');
} else {
Yii::$app->session->setFlash('ErrorJob', $message);
$this->render('create', ['scheduleList' => $scheduleList, 'model' => $model]);
}
} else {
return $this->render('create', ['scheduleList' => $scheduleList, 'model' => $model]);
}
}
Add return statements here:
if ($state) {
Yii::$app->session->setFlash('SuccessJob', $message);
return $this->redirect('index'); //here
} else {
Yii::$app->session->setFlash('ErrorJob', $message);
return $this->render('create', ['scheduleList' => $scheduleList, 'model' => $model]); //and here
}

Validating content before save in yii2

I am using yii2 for a weigh bridge project
Upon create, the user is redirected to view but my controller doesn't validate the information in such a way that even if data is not entered in the form fields a user is always redirected to view.
How can I implement the validation property
Controller code:
public function actionCreate()
{
$model = new TruckWeight1();
if ($model->load(Yii::$app->request->post()) ) {
$model->time_recorded =date('H:i:s');;
$model->recorded_by =
$model->recorded_date = date('Y-m-d');
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
try this
public function actionCreate()
{
$model = new TruckWeight1();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->time_recorded =date('H:i:s');;
$model->recorded_by =
$model->recorded_date = date('Y-m-d');
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
for more on validation validation

Yii2 : Bad Request (#400) Missing required parameters: id

My controller :
public function actionCreate()
{
$model = new CreateBookings();
if ($model->load(Yii::$app->request->post()))
{
$imageName = $model->primary_name;
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs('uploads/'.$imageName.'.'.$model->file->extension);
$model->id_image = 'uploads/'.$imageName.'.'.$model->file->extension;
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else
{
return $this->render('create', [
'model' => $model,
]);
}
}
Getting this error on submitting my form, dont know what's wrong with it..
Tried with $model->save(false); ..but not working as well
Try with getPrimaryKey() method:
public function actionCreate()
{
$model = new CreateBookings();
if ($model->load(Yii::$app->request->post()))
{
$imageName = $model->primary_name;
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs('uploads/'.$imageName.'.'.$model->file->extension);
$model->id_image = 'uploads/'.$imageName.'.'.$model->file->extension;
if($model->save())
{
$lastInsertID = $model->getPrimaryKey();
return $this->redirect(['view', 'id' => $lastInsertID]);
}
else
{
// print_r($model->getErrors()); => check whether any validation errors are there
}
} else
{
return $this->render('create', [
'model' => $model,
]);
}
}

Categories