Обновление записи формы yii с загруженным файлом выдает ошибку, если я не присоединяю файл снова - PullRequest
0 голосов
/ 14 января 2020

когда я создаю новую запись в форме yii с загруженным файлом, она работает нормально, но когда я обновляю ihave, чтобы прикрепить файл снова, иначе это выдаст ошибку, вот мой файл контроллера, пожалуйста, скажите мне, в чем моя ошибка мой загруженный файл - это изображение, я хочу изменить одно поле, скажем, дату и оставить все как есть, включая загруженный файл, но если не прикреплять файл снова, это выдаст ошибку

<?php

namespace app\controllers;

use Yii;
use app\models\JetskiDamageSettlementAgreement;
use app\models\JetskiDamageSettlementAgreementSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
 * JetskiDamageSettlementAgreementController implements the CRUD actions for JetskiDamageSettlementAgreement model.
 */
class JetskiDamageSettlementAgreementController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all JetskiDamageSettlementAgreement models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new JetskiDamageSettlementAgreementSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single JetskiDamageSettlementAgreement model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new JetskiDamageSettlementAgreement model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new JetskiDamageSettlementAgreement();

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

            // get the instance of the uploaded file
            $model->damage_image = UploadedFile::getInstance($model, 'damage_image');
            $image_name = $model->customer_name.'.'.$model->damage_image->extension;
            $image_path = 'attachments/' .$image_name;
            $model->damage_image->saveAs($image_path);
            $model->damage_image = $image_path;

            $model->agreement_date = date ('y-m-d h:m:s');
            $model->save();
            return $this->redirect(['view', 'id' => $model->agreement_id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing JetskiDamageSettlementAgreement model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $model->damage_image = UploadedFile::getInstance($model, 'damage_image');
            $image_name = $model->customer_name.'.'.$model->damage_image->extension;
            $image_path = 'attachments/' .$image_name;
            $model->damage_image->saveAs($image_path);
            $model->damage_image = $image_path;

            $model->save();
            return $this->redirect(['view', 'id' => $model->agreement_id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing JetskiDamageSettlementAgreement model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the JetskiDamageSettlementAgreement model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return JetskiDamageSettlementAgreement the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = JetskiDamageSettlementAgreement::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

1 Ответ

0 голосов
/ 14 января 2020

Из того, что я понимаю, вы получаете ошибку из-за ваших правил, установленных для этой модели. В правилах модели это поле для файла установлено на , обязательное для всех сценариев ios.

Одно из возможных решений - установить обязательное поле только в сценарии insert и оставить сценарий update необязательным для поля. Но это действительно зависит от бизнес-логики c, которую вы должны удовлетворить.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...