Yii2 upload some file but some file not - yii2

In my Yii web I try to upload mp3 files but the weired is that some files get uploaded but some files not, I don't understand they have the same extension same size but don't uploaded ; My two files are
1 - beautiful_violin.mp3, size is 394 KB, type of file : MP3 Format Sound (.mp3)
2 - guitar_vs_violin.mp3, size is 400 KB, type of file : MP3 Format Sound (.mp3)
the 1st song upload , but the second song not uploaded; and it's happen with other mp3, upload some file and some files not.
I'm not using multiple upload, I upload one file per post; It's single file upload.
my model is :
public $PMediaFile;
public function rules()
{
return [
[['post_text'], 'string'],
[['post_crdate', 'post_update'], 'safe'],
[['post_status', 'post_likeplus', 'post_likemoin', 'permission_id', 'filestype_id', 'channel_id', 'user_id'], 'integer'],
[['permission_id', 'filestype_id', 'channel_id', 'user_id'], 'required'],
[['post_title', 'post_uid'], 'string', 'max' => 300],
[['post_file', 'post_thimage', 'post_bgimage', 'post_cssclass', 'post_cssid'], 'string', 'max' => 350],
[['post_icon'], 'string', 'max' => 50],
[['post_title'], 'unique'],
[['PMediaFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'mp3', 'maxSize'=>2000000, 'tooBig' => 'Limit is 2M'],
[['channel_id'], 'exist', 'skipOnError' => true, 'targetClass' => Channel::className(), 'targetAttribute' => ['channel_id' => 'channel_id']],
[['filestype_id'], 'exist', 'skipOnError' => true, 'targetClass' => Filestypes::className(), 'targetAttribute' => ['filestype_id' => 'filestype_id']],
[['permission_id'], 'exist', 'skipOnError' => true, 'targetClass' => Permission::className(), 'targetAttribute' => ['permission_id' => 'permission_id']],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'user_id']],
];
}
in my controller
$isMember = AxChnPermission::ChannelMemberChnNID($this->chn_nid);
if ($isMember)
{
$model = new PostMedia(); $model_Permission = new Permission;
$chn_id = $isMember->channel->channel_id;
$chn_uid = $isMember->channel->channel_uid;
$chn_folder = $isMember->channel->channel_folder;
if ($model->load(Yii::$app->request->post()) )
{
AxPostMedia::CreateMedia($model, $chn_id, $chn_folder);
header('Location: ' . Url::current() );
exit;
}
return $this->render('/post-insert/widget/_formInsertMedia', [
'model' => $model,
'model_Permission' => $model_Permission,
]);
}
AxPostMedia :
class AxPostMedia
{
public function UploadAudio($MPMEDIA, $MAUDIO, $ly_MediaName, $ly_MediaFolder)
{
mkdir($ly_MediaFolder, 0777, true);
$MPMEDIA->PMediaFile->saveAs($ly_MediaFolder .'/'. $ly_MediaName . '.' . $MPMEDIA->PMediaFile->extension);
$MAUDIO->audio_path = $ly_MediaFolder .'/'. $ly_MediaName . '.' . $MPMEDIA->PMediaFile->extension;
$MAUDIO->save(false);
}
public static function CreateMedia($MPMEDIA, $CHNID, $chn_folder)
{
$USRID = Yii::$app->user->id;
$css_and_folder = AxValuePost::CssID();
$MPMEDIA->user_id = $USRID;
$MPMEDIA->channel_id = $CHNID;
$MPMEDIA->post_uid = AxValuePost::PSTUID();
$MPMEDIA->post_cssid = AxValuePost::CssID();
$MPMEDIA->post_update = time();
$ly_MediaName = AxValuePost::FileName();
$MPMEDIA->PMediaFile = UploadedFile::getInstance($MPMEDIA, 'PMediaFile');
if ($MPMEDIA->PMediaFile->extension == 'mp3')
{
$MPMEDIA->filestype_id = 300;
}
$ly_MediaFolder = AxValuePost::PostFolder($chn_folder, $css_and_folder, $MPMEDIA->PMediaFile->extension);
if ($MPMEDIA->PMediaFile->extension === 'mp3')
{
if ($MPMEDIA->save())
{
$MAUDIO = new Audio;
$MAUDIO->post_id = $MPMEDIA->post_id;
$MAUDIO->channel_id = $CHNID;
$MAUDIO->user_id = $USRID;
(new self)->UploadAudio($MPMEDIA, $MAUDIO, $ly_MediaName, $ly_MediaFolder);
}
}
return $MPMEDIA->save(false);
}
}
my view is :
<?php $form = ActiveForm::begin(['options' => ['id' => 'upload-media-form', 'enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'PMediaFile')->fileInput() ?>
<?= $form->field($model, 'post_text')->textarea(['rows' => 2]) ?>
<?= $form->field($model, 'permission_id')->dropdownList($model_Permission->PermissionType()) ?>
<div class="text-right"><?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?></div>
<?php ActiveForm::end(); ?>

Related

Yii2 uploadfile image from model method beforeSave

i try to upload 4 or less images, the ajax validation do not return any error, but on submit i get the follow:
"errors": {
"imageFiles": [
"Please upload a file."
]
}
attr:
/**
* #var UploadedFile[]
*/
public $imageFiles;
Rules:
return [
[['imageFiles'], 'required', 'on' => self::REPORT_STEP1],
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'maxFiles' => 4],
];
BeforeSave:
public function beforeSave($insert)
{
$files_urls = [];
$this->imageFiles = UploadedFile::getInstances($this, 'imageFiles');
foreach ($this->imageFiles as $file) {
$path = Url::to(['/uploads/reports/'], true) . Yii::$app->security->generateRandomString() . '.' . $file->extension;
$file->saveAs($path);
$files_urls[] = $file->name;
}
$this->img_url = json_encode($files_urls);
return parent::beforeSave($insert); // TODO: Change the autogenerated stub
}
Form:
<?php $form = ActiveForm::begin([
'enableAjaxValidation' => true,
'options' => [
'enctype' => 'multipart/form-data'
]
]) ?>
<?= $form->field($model, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<div class="form-group">
<?= Html::submitButton('Siguiente', ['class' => 'btn btn-standard']) ?>
</div>
<?php ActiveForm::end() ?>

How to populate saved multiple values from junction table into dropdown in YII2?

I got an error message, when i want to load back saved elements on update form.
Controller
$contentCategory = ContentCategory::find()
->where(['content_id' => $id])->all();
View
<?= $form->field($contentCategory, 'category_id')
->dropdownList(ArrayHelper::map(Category::find()->all(),'id','title'),
['prompt'=>'Select Category', 'multiple' => 'multiple']
)->label('Add categories'); ?>
The error message.
Call to a member function isAttributeRequired() on array
If i change the all() method to one() it's works but select only one element (of course).
Update:
#scaisEdge I'm using a content_category junction table to insert relations contents with categories.
content_id category_id
1 2
1 3
Model
public function rules()
{
return [
[['content_id', 'category_id'], 'integer'],
[['category_id'], 'exist', 'skipOnError' => true, 'targetClass' => Category::className(), 'targetAttribute' => ['category_id' => 'id']],
[['content_id'], 'exist', 'skipOnError' => true, 'targetClass' => Content::className(), 'targetAttribute' => ['content_id' => 'id']],
];
}
The trouble in that you use $contentCategory array of founded models as form field model.
I think you should just change $contentCategory variable from your view on your certain model like $model = ContentCategory::findOne($id);
#Csaba Faragó
$arr = array();
$colorarr=array();
foreach ($detmodel as $key => $detailm){
//$detailm;
$id = $detailm['productid'];
$sid = $detailm['sizeid'];
$sidex= explode(",",$sid);
$i = 0;
foreach($sidex as $size_id)
{
$val = $sidex[$i];
$val = (int)$val;
array_push($arr, $val);
$i++;
}
<?php $sizelist = ArrayHelper::map(Size::find()->all(),'id','size');
// $idd = '4';
?>
<?php
$detailm->sizeid = $arr;
// print_r($detailm->sizeid);
?>
<?= $form->field($detailm, 'sizeid')->widget(Select2::classname(), [
'data' => $sizelist,
'language' => 'de',
'options' => ['placeholder' => 'Select sizes ...','multiple' => true],
'pluginOptions' => [
'tags' => true,
'tokenSeparators' => [',', ' '],
'maximumInputLength' => 10
],
]);
?>
do all this in view page
I have found a solution here. He is perfectly solve my issue.

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.

PHP - Yii 2.0 Multiple images are save in folder but not saved in database

I have used use kartik\file\FileInput; (extension) for saving multiple images from single form submit.
The images are save locally but are not saving in the database.
Here is my Model Code media.php
namespace app\models;
use yii\web\UploadedFile;
class Media extends \yii\db\ActiveRecord
{
public function rules(){
return [
[['title'], 'file', 'skipOnEmpty' => false, 'extensions' => ['gif', 'jpg', 'png', 'jpeg', 'JPG', 'JPEG', 'PNG', 'GIF'], 'checkExtensionByMimeType' => false ,'maxFiles' => 4, 'maxSize' => 1024 * 1024 * 1024],
[['extension'], 'string', 'max' => 6],
];
}
Controller code:
if ($mediamodel->load ( Yii::$app->request->post () )) {
$title = UploadedFile::getInstances ( $mediamodel, 'title' );
foreach ($title as $key => $file) {
$file->saveAs(Yii::$app->basePath . '/web/images/hotel/'. $file->baseName . '.' . $file->extension);}
foreach ($title as $key => $file){
echo $mediamodel->title."*********";
$mediamodel->title = $file->baseName . '.' . $file->extension;
echo " \Title: ".$mediamodel->title;
$mediamodel->save ();
}
}
My view code:
use kartik\file\FileInput;
$form = ActiveForm::begin([ 'layout' => 'horizontal', {label}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}",
'fieldConfig' => ['horizontalCssClasses' => ['label' => 'col-md-3','offset' => 'col-md-offset-2','wrapper' => 'col-md-4', 'error' => '','hint' => '',],],'
options' => [ 'class' => 'form-horizontal', 'enctype' => 'multipart/form-data', ], ]);?>
<?php echo $form->field($mediamodel, 'title[]')->widget(FileInput::classname(), ['options'=>['multiple' => true]]);
Html::submitButton($model->isNewRecord ? 'Add' : 'Update');
use
$mediamodel->save (false);
instead of
$mediamodel->save ();
// You should handle errors like this.
if(!$mediamodel->save()){
// handle the errors of model.
var_dump($mediamodel->getErrors());
}

Updating Image in Yii2

While updating image using Yii2 I'm facing a problem with the validation.Its always asking me to upload an image. But I don't want this. Always updating an image is not necessary.
I tried skipOnEmpty but its not working properly it cause effect while uploading a photo, which is also incorrect.
Please help!!
Model
public function rules()
{
return [
[['carid', 'name'], 'required'],
[['carid', 'coverphoto', 'status'], 'integer'],
[['name'], 'string', 'max' => 200],
[['imageFiles'], 'image','extensions' => 'png, jpg, jpeg, gif', 'maxFiles' => 4, 'minWidth' => 100, 'maxWidth' => 800, 'minHeight' => 100, 'maxHeight'=>600,'skipOnEmpty' => true],
];
}
Controller
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->photoid]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
You should to use scenario for update.
Like as,
Add on condition in model's rule for applying scenario .
[['imageFiles'], 'image','extensions' => 'png, jpg, jpeg, gif', 'maxFiles' => 4, 'minWidth' => 100, 'maxWidth' => 800, 'minHeight' => 100, 'maxHeight'=>600,'skipOnEmpty' => true, 'on' => 'update-photo-upload'],
And use that scenario in controller's action.
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->scenario = 'update-photo-upload';
........
.....
}
try rule as
[
['imageFiles'], 'file',
'extensions' => 'png, jpg, jpeg, gif',
'mimeTypes' => 'image/jpeg, image/png',
'maxFiles' => 4,
'minWidth' => 100,
'maxWidth' => 800,
'minHeight' => 100,
'maxHeight'=>600,
'skipOnEmpty' => true
],
This is working in my case, hope it works for you too.
**Your View Like This**
<?php use yii\widgets\ActiveForm;?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'imageFiles')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end() ?>
*** Your Controller Like This******
use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;
class SiteController extends Controller
{
public function actionUpdate()
{
$model = new UploadForm ();
$model->scenario = 'update';
if (Yii::$app->request->isPost) {
$model->imageFiles= UploadedFile::getInstance($model, 'imageFiles');
if ($model->upload()) {
// file is uploaded successfully
return;
}
}
return $this->render('update', ['model' => $model]);
}
}
***** Your ModelLike This ******
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
/**
* #var UploadedFile[]
*/
public $imageFiles;
public function rules()
{
return [
[['carid', 'name'], 'required'],
[['carid', 'coverphoto', 'status'], 'integer'],
[['name'], 'string', 'max' => 200],
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 4,'on'=>'update'],
];
}
public function upload()
{
if ($this->validate()) {
foreach ($this->imageFiles as $file) {
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
}
return true;
} else {
return false;
}
}
function scenario()
{
return [
'create' => ['imageFiles ', 'carid','name','coverphoto','status'],
'update' => ['imageFiles ', 'carid','name','coverphoto','status'],
];
}
}