Yii2 Validation: Image may not be empty - yii2

I use ActiveRecord and I want to upload an image. But Yii always says that the fileInput is empty.
My model has an extra attribute called "image" and the rules are
[['image'], 'required', 'on' => 'new'],
[['image'], 'image', 'extensions' => 'png, jpg'],
And I use this Code in the controller
$model = new Picture();
$model->scenario = 'new';
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->image = UploadedFile::getInstance($model, 'image');
$model->image->saveAs($model->savePath($this->plugin).'/'.$model->id.'.jpg');
}
What am I doing wrong?

Below code is working for me, hope it will help you,
[['logo'], 'required', 'on' => 'create'],
[['logo'], 'file', 'skipOnError' => true,'extensions' => 'png, jpg, gif'],
$model = new Company();
$model->scenario = 'create';
if ($model->load(Yii::$app->request->post())) {
$logo = UploadedFile::getInstance($model, 'logo');
if (!is_null($logo)) {
$model->logo = $logo->name;
if($model->validate()) {
$dirpath = dirname(getcwd());
$logo->saveAs($dirpath . '/admin/uploads/' . $logo->baseName . '.' . $logo->extension);
$model->save();
return $this->redirect(['view', 'id' => $model->Id]);
}
}
}

Related

yii\base\ErrorException Use of undefined constant logo - assumed 'logo' (this will throw an Error in a future version of PHP)

I installed web apps for Library Management, when I try to upload logo for the library, it give me error like this
Unknown Property – yii\base\UnknownPropertyException
Use of undefined constant logo - assumed 'logo' (this will throw an Error in a future version of PHP)
This is my stack trace:
1. in /otka/app/src/web/backend/modules/setting/umum/controllers/DataPerpustakaanController.php at line 44
// $model->NamaLokasiPerpustakaan = Yii::$app->config->get('NamaLokasiPerpustakaan');
$model->JenisPerpustakaan = Yii::$app->config->get('JenisPerpustakaan');
$model->IsUseKop = Yii::$app->config->get('IsUseKop');
if ($model->load(Yii::$app->request->post())) {
$model->logo = UploadedFile::getInstance($model, 'logo');
$temp_logo = ($model->logo != "" ? logo : kop);
$model->image = UploadedFile::getInstance($model, $temp_logo);
if($model->image!='')
{
$files_uploaded = '../uploaded_files/aplikasi/' . "temp_image" . '.' . "png";
$model->image->saveAs($files_uploaded,false);
$mimetype=DirectoryHelpers::mimeType($files_uploaded);
if ($mimetype){
unlink($files_uploaded);
2. in /otka/app/src/web/backend/modules/setting/umum/controllers/DataPerpustakaanController.php at line 44– yii\base\ErrorHandler::handleError(2, 'Use of undefined constant logo -...', '/otka/app/src/web/backend/module...', 44, ...)
3. backend\modules\setting\umum\controllers\DataPerpustakaanController::actionIndex()
4. in /otka/app/src/web/vendor/yiisoft/yii2/base/InlineAction.php at line 55- call_user_func_array([backend\modules\setting\umum\controllers\DataPerpustakaanController, 'actionIndex'], [])
5. in /otka/app/src/web/vendor/yiisoft/yii2/base/Controller.php at line 154– yii\base\InlineAction::runWithParams([])
6. in /otka/app/src/web/vendor/yiisoft/yii2/base/Module.php at line 454– yii\base\Controller::runAction('index', [])
7. in /otka/app/src/web/vendor/yiisoft/yii2/web/Application.php at line 84– yii\base\Module::runAction('setting/umum/data-perpustakaan/i...', [])
8. in /otka/app/src/web/vendor/yiisoft/yii2/base/Application.php at line 375– yii\web\Application::handleRequest(yii\web\Request)
This is the function line in DataPerpustakaanController.php
<?php
namespace backend\modules\setting\umum\controllers;
use Yii;
use yii\base\DynamicModel;
use yii\web\UploadedFile;
use common\components\DirectoryHelpers;
class DataPerpustakaanController extends \yii\web\Controller
{
public function actionIndex()
{
$model = new DynamicModel([
'NamaPerpustakaan',
//'NamaLokasiPerpustakaan',
'JenisPerpustakaan',
'IsUseKop',
'logo',
'kop',
'image',
]);
$model->addRule([
'NamaPerpustakaan',
//'NamaLokasiPerpustakaan',
'JenisPerpustakaan', 'IsUseKop',], 'required'
);
$model->NamaPerpustakaan = Yii::$app->config->get('NamaPerpustakaan');
// $model->NamaLokasiPerpustakaan = Yii::$app->config->get('NamaLokasiPerpustakaan');
$model->JenisPerpustakaan = Yii::$app->config->get('JenisPerpustakaan');
$model->IsUseKop = Yii::$app->config->get('IsUseKop');
if ($model->load(Yii::$app->request->post())) {
$model->logo = UploadedFile::getInstance($model, 'logo');
$temp_logo = ($model->logo != "" ? logo : kop); //**This is line 44**
$model->image = UploadedFile::getInstance($model, $temp_logo);
if($model->image!='')
{
$files_uploaded = '../uploaded_files/aplikasi/' . "temp_image" . '.' . "png";
$model->image->saveAs($files_uploaded,false);
$mimetype=DirectoryHelpers::mimeType($files_uploaded);
if ($mimetype){
unlink($files_uploaded);
if ($model->logo != "") {
$model->image->saveAs('../uploaded_files/aplikasi/' . "logo_perpusnas_2015" . '.' . "png");
} else{
$model->image->saveAs('../uploaded_files/aplikasi/' . "kop" . '.' . "png");
}
}
else {
Yii::$app->getSession()->setFlash('error', [
'type' => 'error',
'duration' => 500,
'icon' => 'fa fa-info-circle',
'message' => Yii::t('app', 'Failed Save'),
'title' => 'Info',
'positonY' => Yii::$app->params['flashMessagePositionY'],
'positonX' => Yii::$app->params['flashMessagePositionX']
]);
}
}
if ($model->validate()) {
Yii::$app->config->set('NamaPerpustakaan', Yii::$app->request->post('DynamicModel')['NamaPerpustakaan']);
//Yii::$app->config->set('NamaLokasiPerpustakaan', Yii::$app->request->post('DynamicModel')['NamaLokasiPerpustakaan']);
Yii::$app->config->set('JenisPerpustakaan', Yii::$app->request->post('DynamicModel')['JenisPerpustakaan']);
Yii::$app->config->set('IsUseKop', Yii::$app->request->post('DynamicModel')['IsUseKop']);
Yii::$app->getSession()->setFlash('success', [
'type' => 'info',
'duration' => 500,
'icon' => 'fa fa-info-circle',
'message' => Yii::t('app', 'Success Save'),
'title' => 'Info',
'positonY' => Yii::$app->params['flashMessagePositionY'],
'positonX' => Yii::$app->params['flashMessagePositionX']
]);
}
else {
Yii::$app->getSession()->setFlash('error', [
'type' => 'error',
'duration' => 500,
'icon' => 'fa fa-info-circle',
'message' => Yii::t('app', 'Failed Save'),
'title' => 'Info',
'positonY' => Yii::$app->params['flashMessagePositionY'],
'positonX' => Yii::$app->params['flashMessagePositionX']
]);
}
return $this->redirect(['index']);
} else {
return $this->render('index', [
'model' => $model,]);
}
}
}
How to fix this problem?
I solve this problem, so in line 44 there is code
$temp_logo = ($model->logo != "" ? logo : kop);
change it like this
$temp_logo = ($model->logo != "" ? 'logo' : 'kop');

Save multiple selections from a listbox - Yii2

I have made a Listbox depend on a dropDownList, when selecting an option from the dropDownList brings me a list of data that is added to the Listbox, it works to save a single option but the problem occurs when trying to save multiple selections, I cannot save more than 1 option, I have tried to add a foreach in my controller but it throws an error.
DropDownList
<?php echo $form->field($model, 'group_id')->widget(Select2::classname(), [
'data' => $seccion->lgrupo, //I get the group list
'size' => Select2::MEDIUM,
'theme' => Select2::THEME_BOOTSTRAP,
'options' => [
'placeholder' => '-- '.Yii::t('backend', 'Select').' --',
'onchange'=>'
$.post( "lists?id="+$(this).val(), function( data ) {//I get the list of people registered in the group and send it to the listbox
$( "select#assignment-user_id" ).html( data );
});',
],
'pluginOptions' => [
'allowClear' => true,
],
'addon' => [
'prepend' => [
'content' => Html::icon('building')
],
]
]); ?>
ListBox
<?php echo $form->field($model2, 'users_id')->listBox([] ,['multiple'=>true,'size'=>17]
); ?>
Groups Controller
public function actionCreate()
{
$model = new Groups();
$model2 = new Assignment();
$seccion = new Group();
if ($model->load(Yii::$app->request->post()) && $model2->load(Yii::$app->request->post())) {
if ($model->save(false)) {
foreach ($model2->users_id as $i => $as) {
$as->assign_group_id = $model->id_group_list;
if ($model2->save()) {
} else {
// error in saving model
}
}
return $this->redirect(['view', 'id' => $model->id_group]);
}
}
return $this->render('create', [
'model' => $model,
'model2' => $model2,
'seccion' => $seccion,
]);
}
Tables
I hope your can tell me what I'm doing wrong.
public function actionCreate()
{
$model = new Groups();
$model2 = new Assignment();
$seccion = new Group();
if ($model->load(Yii::$app->request->post()) && $model2->load(Yii::$app->request->post())) {
if ($model->save(false)) {
foreach ($model2->users_id as $user_id) {
$assignmentModel = new Assignment();
$assignmentModel->user_id= $user_id;
$assignmentModel->assign_group_id = $model->id_group_list;
//$assignmentModel->area= ''; //if you want to set some value to these fields
//$assignmentModel->assignment= '';
if ($assignmentModel->save()) {
} else {
// error in saving model
}
}
return $this->redirect(['view', 'id' => $model->id_group]);
}
}
return $this->render('create', [
'model' => $model,
'model2' => $model2,
'seccion' => $seccion,
]);
}

Trying to get property of non-object while using kartik-v for image uploading in Yii2

I'm using yii2-widget-fileinput for an image uploading in a form.
When I click on upload or the create button I get Trying to get property of non-object error in controller.
Controller
public function actionCreate()
{
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/uploads/';
$model = new Ads();
$provinces = ArrayHelper::map(Province::find()->all(), 'name', 'name');
if ($model->load(Yii::$app->request->post())){
$image = UploadedFile::getInstances($model, 'image');
$model->filename = $image->name;
$ext = end((explode(".", $image->name)));
$avatar = Yii::$app->security->generateRandomString().".{$ext}";
$path = Yii::$app->params['uploadPath'].$avatar;
if ($model->save()) {
$image->saveAs($path);
$model->image_adr = $path;
return $this->redirect(['view', 'id' => $model->id]);
}else{
echo "error on saving the model";
}
}
return $this->render('create', [
'model' => $model,
'provinces'=>$provinces,
]);
}
model rules
public function rules()
{
return [
[['type', 'explanation', 'cost', 'province_name', 'address'], 'required'],
[['type', 'explanation', 'image_adr', 'address'], 'string'],
[['cost'], 'integer'],
[['province_name'], 'string', 'max' => 20],
[['province_name'], 'exist', 'skipOnError' => true, 'targetClass' => Province::className(), 'targetAttribute' => ['province_name' => 'name']],
[['image'],'safe'],
[['image'], 'file', 'extensions'=>'jpg, gif, png', 'maxFiles'=>3,],
];
and finnally the view
<?= $form->field($model, 'image[]')->widget(FileInput::classname(), [
'options'=>['accept'=>'image/*', 'multiple'=>true],
'pluginOptions'=>['allowedFileExtensions'=>['jpg','gif','png'], 'overwriteInitial'=>false,]
]); ?>
the problem should refer to this part in the controller I think
$image = UploadedFile::getInstances($model, 'image');
An image of the error might be helpful
You should check first is image in post or not.
....
$image = UploadedFile::getInstances($model, 'image'); //getInstanceByName
if (!empty($image))
$model->filename = $image->name;
.....
if ($model->save()) {
if (!empty($image))
$image->saveAs($path);
.........
Make sure in your form ency type is added:
$form = ActiveForm::begin([
'id' => 'form_id',
'options' => [
'class' => 'form_class',
'enctype' => 'multipart/form-data',
],
]);
The problem is when you're using UploadedFile::getInstances($model, 'image'); you should work with foreach or treat it like an array.
Something that made me a problem was that even if you're using UploadedFile::getInstanc (notice the obsoleted s in the end) you should still treat it like an array and in all parts you should use $image[0], not $iamge lonely.

Call to a member function saveAs() on null(does't work skipOnEmpty)

I can't update a page without of upload image.Even if I write skipOnEmpty in the rules it doesn't work . What do I wrong?
This is a controller
if ($model->load(Yii::$app->request->post())){
//represent the uploaded file as an instance
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
//save path to image in db
$model->image = '/images/' . $model->imageFile->baseName . '.' . $model->imageFile->extension;
//save changes in db
$model->save();
//upload image on server
$model->upload();
Yii::$app->session->setFlash('success',
"Product is successfully updated!");
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
This is a model
public function rules()
{
return [
[['name', 'category', 'code', 'price', 'availability', 'brand', 'description'], 'required'],
[['category', 'code', 'availability', 'is_new', 'is_recommended', 'status'], 'integer'],
[['price'], 'number'],
[['description'], 'string'],
[['name','image', 'brand'], 'string', 'max' => 255],
[['imageFile'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
];
}
uploading of a file to the server
public function upload()
{
if ($this->validate()) {
$this->imageFile->saveAs('images/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
return true;
} else {
return false;
}
}
change your controller code like below:
if ($model->load(Yii::$app->request->post())){
//represent the uploaded file as an instance
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
//save path to image in db
if($model->imageFile){
$model->image = '/images/' . $model->imageFile->baseName . '.' . $model->imageFile->extension;
}
//save changes in db
$model->save();
//upload image on server
if($model->imageFile){
$model->upload();
}
Yii::$app->session->setFlash('success',
"Product is successfully updated!");
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
Set a hidden field in your upload form like below:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'imageFile')->fileInput() ?>
<?if(!$model->isNewRecord):
echo Html::activeHiddenInput($model, 'imageFile');
endif;
?>

cant import data csv to database in yii2

I am very new to web development.
I'm newbie in here, my first question in stackoverflow..
i am confused what error on code, Code will be store data array csv to a database,
sorry my bad english.
Controller
public function actionUpload()
{
$model = new Skt();
//error_reporting(E_ALL);
//ini_set('display_error', 1);
if ($model->load(Yii::$app->request->post())) {
$file = UploadedFile::getInstance($model, 'file');
$filename = 'Data.' . $file->extension;
$upload = $file->saveAs('uploads/' . $filename);
if ($upload) {
define('CSV_PATH', 'uploads/');
$csv_file = CSV_PATH . $filename;
$filecsv = file($csv_file);
foreach ($filecsv as $data) {
$modelnew = new Skt();
$hasil = explode(",", $data);
$no_surat= $hasil[0];
$posisi= $hasil[1];
$nama= $hasil[2];
$tgl_permanen= $hasil[3];
$grade= $hasil[4];
$tgl_surat= $hasil[5];
$from_date = $hasil[6];
$to_date = $hasil[7];
$modelnew->no_surat = $no_surat;
$modelnew->posisi = $posisi;
$modelnew->nama = $nama;
$modelnew->tgl_permanen = $tgl_permanen;
$modelnew->grade = $grade;
$modelnew->tgl_surat = $tgl_surat;
$modelnew->from_date = $from_date;
$modelnew->to_date = $to_date;
$modelnew->save();
//print_r($modelnew->validate());exit;
}
unlink('uploads/'.$filename);
return $this->redirect(['site/index']);
}
}else{
return $this->render('upload',['model'=>$model]);
}
return $this->redirect(['upload']);
}
Model
class Skt extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'skt';
}
public $file;
public function rules()
{
return [
[['file'], 'required'],
[['file'], 'file', 'extensions' => 'csv', 'maxSize' => 1024*1024*5],
[['no_surat'], 'required'],
[['tgl_surat', 'from_date', 'to_date'], 'string'],
[['no_surat', 'posisi', 'nama', 'tgl_permanen', 'grade'], 'string', 'max' => 255],
];
}
public function attributeLabels()
{
return [
'no_surat' => 'No Surat',
'posisi' => 'Posisi',
'nama' => 'Nama',
'tgl_permanen' => 'Tgl Permanen',
'grade' => 'Grade',
'tgl_surat' => 'Tgl Surat',
'from_date' => 'From Date',
'to_date' => 'To Date',
'file' => 'Select File'
];
}
}
thanks for helping..
change your code to the following to output the errors which could happen when you try to save. Errors could occur depending on your model rules.
if (!$modelnew->save()) {
var_dump($modelnew->getErrors());
}
getErrors() from Api
A better approach is to use exceptions to throw and catch errors on your import. Depends if you want to skip csv lines on errors or not.
finally it working with change this $hasil = explode(";", $data);