I
I
Igor Vasiliev2016-07-07 23:10:28
Yii
Igor Vasiliev, 2016-07-07 23:10:28

Sending a file to Yii2 Basic does not work, what's wrong?

here is the controller:

public function actionIndex() {
        $page = Indexpage::find()->one();
        
        $model = new UploadForm();
            if ($model->load(Yii::$app->request->post()) && $model->upload(Yii::$app->params['adminEmail'])) {
                $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
                Yii::$app->session->setFlash('contactFormSubmitted');
                $email  = new Zakaz();
                $email-> attributes = $model->attributes;
                if(!$email->save()){
                    throw new \yii\web\HttpException(500, 'Невозможно сохранить');
                }
                return $this->refresh();
            } 

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

here is the model:
<?php
    namespace app\models;
    
    use Yii;
    use yii\base\Model;

class UploadForm extends Model {
    
    public static function tableName() {
        return '1038_zakaz';
    } 

    public $id;
    public $fio;
    public $email;
    public $phone;
    public $city;
    public $sfera;
    public $words;  
    public $imageFile;
    public $data;

    public function rules()
    {
        return [
            [['fio', 'email', 'phone', 'city', 'sfera', 'words', 'data'], 'required'],
            ['email', 'email'],
            [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'txt, pdf, png, gif, doc, docx, xlsx, jpg'],
        ];
    }
    
    public function attributeLabels() {
            return [
                //'id' => '',
                'fio' => 'Укажите вашу фамилию имя отчество',
                'email' => 'Укажите ваш электронный адрес',
                'phone' => 'Укажите ваш номер телефона',
                'city' => 'Укажите ваш город',
                'sfera' => 'Выберите услугу',
                'words' => 'Напишите ваше сообщение',
                'imageFile'  => 'Прикрепите файл', 
                'data' => '',
            ];
    }    
    
    public function upload($email) {
        if ($this->validate()) {
            $this->imageFile->saveAs('ru/img/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
            Yii::$app->mailer->compose()
                ->setTo($email)
                ->setFrom([$this->email => $this->fio])
                ->setSubject('Новый заказ')
                ->setHtmlBody('
                    <p>ФИО Заказчика: '.$this->fio.'</p>
                    <p>E-mail: '.$this->email.' </p>
                    <p>Телефон: '.$this->phone.' </p>
                    <p>Город: '.$this->city.' </p>
                    <p>Услуга: '.$this->sfera.' </p>
                    <p>'.$this->words.'</p>
                        <hr/> 
                    <i>Дата получения: '.$this->data.'</i>
                              ')
                ->send();

            return true;
        }
        return false;
    }    
}

here is the view:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
            <?= $form->field($model, 'fio')->textInput(['placeholder' => 'Ваше Ф.И.О.'])->label('') ?>
      <?= $form->field($model, 'email')->widget(MaskedInput::className(), ['clientOptions' => ['alias' =>  'email'],])->textInput(['placeholder' => 'ваше email'])->label('') ?>  
      <?= $form->field($model, 'phone')->widget(MaskedInput::className(), ['mask' => '+7(999) 99-99-999'])->textInput(['placeholder' => 'ваш телефон'])->label('') ?> 
      
            <?php $city = City::find()->orderBy(['c_header' => SORT_ASC,])->all();?> 
            <?php $sc = ['prompt' => 'Ваш город'];?>
            <?php $select = ArrayHelper::map($city, 'c_header', 'c_header')?> 
            <?= $form->field($model, 'city')->dropDownList($select, $sc)->label('') ?> 

            <?php $servis = Servis::find()->all();?>
            <?php $params = ['prompt' => 'Выберите услугу...'];?>
            <?php $itds = ArrayHelper::map($servis,'s_header','s_header'); ?> 
            <?= $form->field($model, 'sfera')->dropDownList($itds,$params)->label('')  ?>

      
            <?= $form->field($model, 'words')->textarea(['rows' => 4])->label('') ?>
            <?= $form->field($model, 'imageFile')->fileInput()->label('') ?>
            
            <?= $form->field($model, 'data')->hiddenInput(['value' => date("d.m.Y в H:i:s")])->label('') ?>
      

      <div class="row"> 
          <div class="col-lg-9">
<?= Html::submitButton('<i class="ionicons ion-paper-airplane"></i> ОТПРАВИТЬ', ['class' => 'btn btn-warning gif', 'style' => 'width:100%;', 'name' => 'contact-button']) ?>
          </div>
          <div class="col-lg-3">
    <button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">
        <i class="ionicons ion-close"></i> закрыть
    </button>  
          </div>
      </div>
      
        <?php ActiveForm::end() ?>

Everything works if you comment out the imageFile variable, the validation works, it sends both to the database and to the mail.
Question: What did I do wrong? Why is the file not being sent? Because without it - everything works and goes. Please tell me what is wrong. Thank you in advance.

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim Fedorov, 2016-07-08
@Isolution666

The first thing that catches your eye is that in the controller you first call $model->upload - which saves the file from the imageFile attribute to the hard disk, and only then assign the file to this attribute $model->imageFile = UploadedFile::getInstance($model, ' imageFile'); And vice versa...

S
Skrolea, 2016-07-07
@Skrolea

So what are the errors?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question