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

wave
Thanapat Aiyasuwan
3,492
สังคมนักพัฒนาระบบ (Community)
Yii2 Upload | Bad Request (#400) Missing required parameters: id

Yii2 Advanced อัพโหลดรูปไม่ได้ ใส่ข้อมูลในฟอร์มได้ทุกอย่าง แต่กดส่งค่าขึ้น Error

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

File backend\views\album\ _form.php

<?= $form->field($model, 'file')->widget(FileInput::classname(), [
    'options' => ['accept' => 'image/*'],
    'pluginOptions' => [
        'initialPreview'=>[],
        'allowedFileExtensions'=>['jpg', 'png','gif'],
        'showPreview' => true,
        'showRemove' => true,
        'showUpload' => false
     ]
   ]); ?>

File backend\models\Album.php

public $file;

public static function tableName()
    {
        return 'album';
    }

    /**
     * @inheritdoc
     */
public function rules()
    {
        return [
            [['album_name', 'album_detail', 'album_cover', 'album_create', 'album_status'], 'required'],
            [['album_create'], 'safe'],
            [['album_status'], 'string'],
            [['file'],'file'],
            [['album_name', 'album_cover'], 'string', 'max' => 100],
            [['album_detail'], 'string', 'max' => 255],
        ];
    }

public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'album_name' => 'Album Name',
            'album_detail' => 'Album Detail',
            'file' => 'Album Cover',
            'album_create' => 'Album Create',
            'album_status' => 'Album Status',
        ];
    }

File backend\controllers\AlbumController.php

public function actionCreate()
    {
        $model = new Album();

        if ($model->load(Yii::$app->request->post()))
        {
            // get the instance of the uploaded file
            $imageName = $model->album_name;
            $model->file = UploadedFile::getInstance($model,'file');
            $model->file->saveAs( 'uploads/'.$imageName.'.'.$model->file->extension );

            // save the path in the db column
            $model->album_cover =  'uploads/'.$imageName.'.'.$model->file->extension;
            $model->save();

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

 

1 ความคิดเห็น

  • มานพ กองอุ่น

ดูเหมือนว่ามันไม่ save ข้อมูลครับ ลองเพิ่มเติมตรง saveAs ครับ

$model->file->saveAs( Yii::getAlias('@webroot').'/uploads/'.$imageName.'.'.$model->file->extension );