Как передать правильно параметры для сохранения данных в базу?

Народ, добро времени. Моя тупя голова ничего не понимает, подскажи что я делаю не так?
Модель
<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "films".
 *
 * @property int $id
 * @property string $title
 * @property string $desk
 * @property string $text
 * @property string $id_alias
 * @property string $id_category
 * @property string $id_theater
 * @property string $data_out
 * @property string $budget
 * @property string $author
 * @property string $imageFile
 *
 * @property Categoryes $category
 * @property Theaters $theater
 * @property Categoryes $alias
 */
class Films extends \yii\db\ActiveRecord
{

    public $imageFile; 
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'films';
    }

    /**
     * @inheritdoc
     */


    public function rules()
    {
        return [
            [['title', 'desk', 'text', 'id_alias', 'id_category', 'id_theater', 'data_out', 'budget', 'author','imageFile'], 'required'],
            [['text'], 'string'],
            [['data_out'], 'safe'],
            [['imageFile'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
            [['title', 'desk', 'id_alias', 'id_category', 'id_theater', 'budget', 'author'], 'string', 'max' => 255],
            [['id_category'], 'exist', 'skipOnError' => true, 'targetClass' => Categoryes::className(), 'targetAttribute' => ['id_category' => 'category']],
            [['id_theater'], 'exist', 'skipOnError' => true, 'targetClass' => Theaters::className(), 'targetAttribute' => ['id_theater' => 'theater']],
            [['id_alias'], 'exist', 'skipOnError' => true, 'targetClass' => Categoryes::className(), 'targetAttribute' => ['id_alias' => 'alias']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Title',
            'desk' => 'Desk',
            'text' => 'Text',
            'id_alias' => 'Id Alias',
            'id_category' => 'Id Category',
            'id_theater' => 'Id Theater',
            'data_out' => 'Data Out',
            'budget' => 'Budget',
            'author' => 'Author',
            'imageFile' => 'Image File',
        ];
    }
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCategory()
    {
        return $this->hasOne(Categoryes::className(), ['category' => 'id_category']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTheater()
    {
        return $this->hasOne(Theaters::className(), ['theater' => 'id_theater']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAlias()
    {
        return $this->hasOne(Categoryes::className(), ['alias' => 'id_alias']);
    }

    public function upload()
    {
        if($this->validate()){
            $this->imageFile->saveAs("img/{$this->imageFile->baseName}.{$this->imageFile->extension}");
            return true;
        } else {

            return false;
        }
    }
}


Метод контролера
public function actionCreate()
    {
        $model = new Films();

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

            $model->imageFile = UploadedFile::getInstance($model,'imageFile');

            if($model->imageFile && $model->upload()) {
                $model->imageFile = $this->imageFile->baseName . '.' . $this->imageFile->extension;
            }
            if($model->save()) {

                return $this->redirect(['creat', 'id' => $model->id]);

            }
        }

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


Форма отправки данных в базу
<?php 

    $params = [
       'promt' => 'не указано'
    ]
     ?>

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

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

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

        <?= $form->field($model, 'text')->textarea(['rows' => 6]) ?>
        
        <?= $form->field($model, 'id_category')->dropDownList(ArrayHelper::map(Categoryes::find()->all(),'category','category'),$params) ?>

        <?= $form->field($model, 'id_alias')->dropDownList(ArrayHelper::map(Categoryes::find()->all(),'alias','alias'),$params) ?>

        <?= $form->field($model, 'data_out')->textInput() ?>

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

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

        <?= $form->field($model, 'id_theater')->dropDownList(ArrayHelper::map(Theaters::find()->all(),'theater','theater'),$params) ?>

        <?= $form->field($model, 'imageFile')->fileInput() ?>

        <div class="form-group">
            <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
        </div>

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


Суть в чем, при отправке я получаю ошибку о том что не докормил одним параметром. На форме это параметр есть и через него идет картинка, в модели он тоже есть. А говорит что нету... :(
5ab7ce6295c4e274773960.png
Что я упускаю, подскажите пожалуйста? Где указать этот самый упущенный параметр?
За ранее спасибо
  • Вопрос задан
  • 69 просмотров
Пригласить эксперта
Ответы на вопрос 1
slo_nik
@slo_nik Куратор тега Yii
Добрый вечер.
Ошибка говорит, что "не имеет значение по умолчанию".
Уберите imageFile из секции required в правилах валидации или в тех же правилах, через параметр default назначайте значение по умолчанию.

Note: большинство валидаторов не обрабатывает пустые входные данные, если их [[yii\base\Validator::skipOnEmpty]] свойство принимает значение по умолчанию true. Они просто будут пропущены во время проверки, если связанные с ними атрибуты являются пустыми. Среди основных валидаторов, только captcha, default, filter, required, и trim будут обрабатывать пустые входные данные.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы