Почему не загружаются несколько файлов?

модель
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "project".
 *
 * @property int $id
 * @property string $title
 * @property string $type
 * @property string $annotation
 * @property string $description
 * @property string|null $date
 * @property float|null $price
 * @property string $files_link
 * @property int|null $customer_id
 * @property int|null $performer_id
 * @property string|null $task_status
 * @property int|null $on_time
 * @property string|null $planned_execution_time
 * @property string|null $actual_execution_time
 * @property int|null $urgently
 *
 * @property Profile $customer
 */
class Project extends \yii\db\ActiveRecord
{
    public $imageFiles;

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

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['title', 'type', 'annotation', 'description'], 'required'],
            [['description', 'files_link'], 'string'],
            [['date', 'planned_execution_time', 'actual_execution_time'], 'safe'],
            [['price'], 'number'],
            [['customer_id', 'performer_id', 'offer_id'], 'integer'],
            [['title', 'type', 'annotation', 'task_status', 'urgently', 'on_time'], 'string', 'max' => 255],
            [['customer_id'], 'exist', 'skipOnError' => true, 'targetClass' => Profile::className(), 'targetAttribute' => ['customer_id' => 'id']],
            [['imageFiles'], 'file', 'extensions' => 'png, jpg, rar, zip', 'maxFiles' => 10],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Заголовок',
            'type' => 'Тип работ',
            'annotation' => 'Аннотация',
            'description' => 'Описание',
            'date' => 'Дата создания',
            'price' => 'Цена',
            'files_link' => 'Ссылки на файлы',
            'customer_id' => 'ИД заказчика',
            'performer_id' => 'ИД исполнителя',
            'offer_id' => 'ИД предложения',
            'task_status' => 'Статус задачи',
            'on_time' => 'Исполнитель обязан выполнить задачу вовремя или допускаются задержки?',
            'planned_execution_time' => 'Дата завершения',
            'actual_execution_time' => 'Фактическое Время Выполнения',
            'urgently' => 'Срочно',
            'imageFiles' => 'Файл проекта'
        ];
    }

    /**
     * Gets query for [[Customer]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getCustomer()
    {
        return $this->hasOne(Profile::className(), ['id' => 'customer_id']);
    }
}


представление
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\project */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="project-form">

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

    <div class="project-row-data">
        <?= $form->field($model, 'title')->textInput(['maxlength' => true, 'class' => 'project-item-data']) ?>
        <?= $form->field($model, 'type')->dropDownList([
            ' ' => 'Выберите необходимое',
            'Водоснабжение и водоотведение' => 'Водоснабжение и водоотведение',
            'Машиностроение' => 'Машиностроение',
            'Разработка сметной документации' => 'Разработка сметной документации',
            'Строительные конструкции' => 'Строительные конструкции',
            'Транспортные объекты' => 'Транспортные объекты',
            'Имитационное моделирование' => 'Имитационное моделирование',
            'Проектирование объектов' => 'Проектирование объектов',
            'Светотехника' => 'Светотехника',
            'Теплоснабжение/Отопление/Вентиляция' => 'Теплоснабжение/Отопление/Вентиляция',
            'Чертежи/Схемы' => 'Чертежи/Схемы',
            'Инженерные изыскания' => 'Инженерные изыскания',
            'Промышленное и гражданское строительство' => 'Промышленное и гражданское строительство',
            'Слаботочные системы' => 'Слаботочные системы',
            'Техническое обследование и обмеры' => 'Техническое обследование и обмеры',
            'Электроснабжение' => 'Электроснабжение',
        ],
            ['options' => [' ' => ['Selected' => true, 'Disabled' => true]], 'class' => 'project-item-data']) ?>
    </div>

    <div class="project-row-data">
        <?= $form->field($model, 'annotation')->textInput(['maxlength' => true]) ?>
    </div>

    <div class="project-row-data">
        <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
    </div>

    <div class="project-row-data">
        <?= $form->field($model, 'planned_execution_time')->textInput(['type' => 'date', 'class' => 'project-item-data']) ?>

        <?= $form->field($model, 'price')->textInput(['class' => 'project-item-data']) ?>
    </div>

    <div class="project-row-data">
        <?= $form->field($model, 'on_time')->radioList(['Да' => 'Да, обязан выполнить вовремя', 'Нет' => 'Нет, допускаются задержки']) ?>
    </div>

    <div class="project-row-data">
        <?= $form->field($model, 'urgently')->radioList(['Да' => 'Да', 'Нет' => 'Нет']) ?>
    </div>

    <div class="project-row-data">
        <?= $form->field($model, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'files/*'])?>
        <?= Html::submitButton('Создать проект', ['class' => 'a-btn']) ?>
    </div>

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

</div>


контроллер
public function actionCreate()
    {
        $model = new Project();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if ($model->imageFiles = UploadedFile::getInstance($model, 'imageFiles')) {
                if (!file_exists('img/profile/' . $model->id)) {
                    FileHelper::createDirectory('img/profile/' . $model->id);
                }

                foreach ($model->imageFiles as $file) {
                    $file->saveAs('files/' . $file->baseName . '.' . $file->extension);
                }
            }

//            $model->date = date("Y-m-d");
//            $model->customer_id = Yii::$app->getUser()->getId();
//            $model->task_status = "Открыт";

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

        return $this->render('create', [
            'model' => $model,
        ]);
    }
  • Вопрос задан
  • 14 просмотров
Пригласить эксперта
Ваш ответ на вопрос

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

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