1

I'm trying to upload multiple images when I create a Post, but only one Image is stored in database, in server all images are saved but in my table only first image is saved but not all so I created function for upload

// Function to upload images
public function CreateGallery($model_Post, $model_Gallery)
{
    $model_Post->Post_id = md5(microtime());
    $model_Post->User_id = Yii::$app->user->id;

    $GLRID = md5(uniqid());

    // file
    $GFolder = 'upload/images/'. $model_Post->Post_id .'/' ;

    mkdir ($GFolder, 0777, true);

    if ( $model_Post->save() ){

        $model_Gallery->GalleryFile = UploadedFile::getInstances($model_Gallery, 'GalleryFile');

        $ly_GalName = uniqid();

        foreach ($model_Gallery->GalleryFile as $GalleryImage) {

            ++$ly_GalName;
            $model_Gallery->Gallery_id = ++$GLRID;
            $model_Gallery->User_id = $model_Post->User_id;
            $model_Gallery->Post_id =  $model_Post->Post_id;

            $GalleryImage->saveAs($GFolder . $GalName . '.' . $GalleryImage->extension);

            $model_Gallery->Gallery_image = $GFolder . $GalName . '.' . $GalleryImage->extension;
        }
        $model_Gallery->save(false);
    }   
}

and inside my controller I add the function I created

public function actionCreate()
{
    $model_Post = new Post(); 
    $model_Gallery = new Gallery;
    $actions_UploadImages = new ActionsUploadImages();

    if ($model->load(Yii::$app->request->post()) ) {

        $actions_UploadImages->CreateGallery($model_Post, $model_Gallery)

        return $this->redirect(['view', 'id' => $model_Post->Post_id]);
    } else {
        return $this->render('create', [
            'model_Post' => $model_Post,
            'model_Gallery' => $model_Gallery,
        ]);
    }
}

and my views/create my code is

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

<?= $form->field($model_Post, 'Post_title')->textInput(['maxlength' => true]) ?>

<?= $form->field($model_Gallery, 'GalleryFile[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>

<?= $form->field($model_Post, 'Post_text')->textarea(['rows' => 2]) ?>

<?= $form->field($model_Post, 'Permission_id')->dropdownList($model_Permission->PermissionList()) ?>

<div class="form-group">
    <?= Html::submitButton($model_Post->isNewRecord ? 'Create' : 'Update', ['class' => $model_Post->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

I tried to change gallery_id to AUTO_INCREMENT but still the same problem, I tried to remove if ( $model_Post->save() ), but I get error from database. Only like it's is now it's save all images on server but in table save only one image.

//// gallery model :

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "gallery".
 *
 * @property string $Gallery_id
 * @property string $Gallery_image
 * @property string $Post_id
 * @property string $User_id
 *
 * @property Post $post
 * @property Userlogin $user
 */
class Gallery extends \yii\db\ActiveRecord
{
    public $GalleryFile;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'gallery';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['Gallery_id', 'Post_id', 'User_id'], 'required'],
            [['Gallery_id'], 'string', 'max' => 200],
            [['Gallery_image'], 'string', 'max' => 350],
            [['Post_id', 'User_id'], 'string', 'max' => 300],
            [['GalleryFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg, gif', 'maxFiles' => 5],
            [['Post_id'], 'exist', 'skipOnError' => true, 'targetClass' => Post::className(), 'targetAttribute' => ['Post_id' => 'Post_id']],
            [['User_id'], 'exist', 'skipOnError' => true, 'targetClass' => Userlogin::className(), 'targetAttribute' => ['User_id' => 'User_id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'Gallery_id' => 'Gallery ID',
            'Gallery_image' => 'Gallery Image',
            'Post_id' => 'Post ID',
            'User_id' => 'User ID',
        ];
    }


    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPost()
    {
        return $this->hasOne(Post::className(), ['Post_id' => 'Post_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(Userlogin::className(), ['User_id' => 'User_id']);
    }

    /**
     * @inheritdoc
     * @return \app\queries\GalleryQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \app\queries\GalleryQuery(get_called_class());
    }
}
4
  • what error does it prints please add the eaxct exception or model error that it displays Commented Mar 29, 2018 at 14:20
  • The error it says : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails Commented Mar 29, 2018 at 23:44
  • add your gallery model Commented Mar 29, 2018 at 23:46
  • I did add my model Commented Mar 30, 2018 at 0:51

2 Answers 2

1

you need write a new model en the for each , like that

Function

  • Create a new model object in the for each .
  • Set the $model_Gallery->save(false); in inside the foreach

    // Function to upload images

    public function CreateGallery($model_Post, $model_Gallery)
    {
        $model_Post->Post_id = md5(microtime());
        $model_Post->User_id = Yii::$app->user->id;
        $GLRID = md5(uniqid());
        // file
        $GFolder = 'upload/images/' . $model_Post->Post_id . '/';
    
        mkdir($GFolder, 0777, true);
    
        if ($model_Post->save()) {
            $model_Gallery->GalleryFile = UploadedFile::getInstances($model_Gallery, 'GalleryFile');
    
            $ly_GalName = uniqid();
    
            foreach ($model_Gallery->GalleryFile as $GalleryImage) {
                $model_GalleryImage = new Gallery;
                ++$ly_GalName;
                $model_GalleryImage->Gallery_id = ++$GLRID;
                $model_GalleryImage->User_id = $model_Post->User_id;
                $model_GalleryImage->Post_id = $model_Post->Post_id;
    
                $GalleryImage->saveAs($GFolder . $GalName . '.' . $GalleryImage->extension);
    
                $model_GalleryImage->Gallery_image = $GFolder . $GalName . '.' . $GalleryImage->extension;
                $model_GalleryImage->save(false); //here , remove 'false' to work validations
            }
    
        }
    } 
    

Controller

when the action load the data ,it should not be like that ?

if ($model_Gallery->load(Yii::$app->request->post()) and  $model_Post->load(Yii::$app->request->post())) {
        //the rest of the code
        }

Please note that we use save(false) to skip over validations inside the models as the user input data... with the user input

Sign up to request clarification or add additional context in comments.

5 Comments

skipping validations is not the solution to the problem you need to validate each image before you insert/save it otherwise the files that are not supported will also be allowed to be uploaded
I know but he wrote it that way, I prefer save () whitout false
I did try this this solution but still not working not save all images on database , but it's save them all on server but not on table
I have made some changes, create the model within the loop, and possible change in the controller in the data load @Bynd
it's working with making the $model_GalleryImage = new Gallery; and remove it from controller. You are genius.
0

All you have to do is iterate $_FILES object using foreach loop and create new model every time. To validate code manage flag for that

1 Comment

"All you have to do is iterate $_FILES", I don't know how to do it. But this solution stackoverflow.com/a/49553996/6562828 work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.