douci1615
2017-02-16 14:03
浏览 44
已采纳

将数据保存到db yii2

I'm trying to save data from my form to db. But when I click "submit" button nothing happened(page is refresh but my db table is blank) what I did wrong? I'm create model which extend ActiveRecord:

class EntryForm extends \yii\db\ActiveRecord
{
    public $id;
    public $name;
    public $email;
    public $age;
    public $height;
    public $weight;
    public $city;
    public $checkboxList;
    public $checkboxList1;
    public $imageFiles;
    public function rules()
    {
        return [
            [['name', 'email','age','height','weight','city','checkboxList','checkboxList1'], 'required'],
            [['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg','maxFiles' => 5],
            ['email', 'email'],
        ];
    }
    public static function tableName()
    {
    return 'form';
    }
    public function attributeLabels()
   {
       return [
           'id' => 'ID',
           'name' => 'name',
           'email' => 'e-mail',
           'age' => 'age',
           'height' => 'height',
           'weight' => 'weight',
           'city' => 'city',
           'checkboxList' => 'technies',
           'checkboxList1' => 'english_level',
           'imageFiles[0]' => 'photo_1',
           'imageFiles[1]' => 'photo_2',
           'imageFiles[2]' => 'photo_3',
           'imageFiles[3]' => 'photo_4',
           'imageFiles[4]' => 'photo_5'
       ];
   }
   public function insertFormData()
   {
       $entryForm = new EntryForm();
       $entryForm->name = $this->name;
       $entryForm->email = $this->email;
       $entryForm->age = $this->age;
       $entryForm->height = $this->height;
       $entryForm->weight = $this->weight;
       $entryForm->city = $this->city;
       $entryForm->checkboxList = $this->checkboxList;
       $entryForm->checkboxList1 = $this->checkboxList1;
       $entryForm->imageFiles = $this->imageFiles;
       return $form->save();
   }
   public function contact($email)
  {
      if ($this->validate()) {
          Yii::$app->mailer->compose()
              ->setTo($email)
              ->setFrom('prozrostl@gmail.com')
              ->setSubject('Email from test app')
              ->setTextBody($this->name + $this->age + $this->height + $this->width + $this->city + $this->checkboxList + $this->checkboxList1 + $this->imageFiles)
              ->send();

          return true;
      } else {
          return false;
      }
  }
    }

then I update my view file to show the form, view it's just easy few fields and upload files button(but all information doesn't save)

<?php $form = ActiveForm::begin([
        'id' => 'my-form',
        'options' => ['enctype' => 'multipart/form-data']
    ]); ?>
    <div class="row">
        <div class="col-lg-6">
            <?= $form->field($entryForm, 'name')->textInput(['class'=>'name_class'])->input('name',['placeholder' => "Имя"])->label(false); ?>
        </div>
        <div class="col-lg-6">
            <?= $form->field($entryForm, 'email')->textInput()->input('email',['placeholder' => "E-mail"])->label(false); ?>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6">
            <?= $form->field($entryForm, 'age')->textInput()->input('age',['placeholder' => "Возраст(полных лет)"])->label(false); ?>
        </div>
        <div class="col-lg-6">
            <?= $form->field($entryForm, 'height')->textInput()->input('height',['placeholder' => "Рост"])->label(false); ?>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6">
            <?= $form->field($entryForm, 'weight')->textInput()->input('weight',['placeholder' => "Вес"])->label(false); ?>
        </div>
        <div class="col-lg-6">
            <?= $form->field($entryForm, 'city')->textInput()->input('city',['placeholder' => "Город проживания"])->label(false); ?>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-3">
            <p><img class="describe_images" src="computer.png"></img>Нужна ли техника в аренду</p>
        </div>
        <?= $form->field($entryForm, 'checkboxList')->checkboxList(['no'=>'Нет', 'yes_camera'=>'Да,только камера', 'yes_both'=>'да,компьютер и камера'])->label(false) ?>
    </div>
    <div class="row">
        <div class="col-lg-3">
            <p><img class="describe_images" src="English.png"></img>Знание английского</p>
        </div>

        <?= $form->field($entryForm, 'checkboxList1')->checkboxList(['starter'=>'Без знания', 'elementary'=>'Базовый', 'intermediate'=>'Средний','up-intermediate'=>'Высокий','advanced'=>'Превосходный'])->label(false) ?>
    </div>
<div class="row">
        <div class="col-lg-6">
<div class="col-lg-6">
            <p class="add_photo"><img class="describe_images" src="photo.png"></img>Добавить фото(до 5 штук)</p>

   </div>
   <div class="col-lg-6">
 <?= $form->field($entryForm, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*','id'=>'gallery-photo-add'])->label(false) ?>
   </div>


        </div>

        <div class="col-lg-6 pixels-line">
            <div class="preview"></div>
        </div>
    </div>
    <div class="form-group">
        <?= Html::submitButton('Отправить', ['class' => 'btn btn-primary']) ?>
    </div>
<?php ActiveForm::end() ?>

and then I add that code to my controller. I created new action ActionForm and put into that code:

public function actionForm()
{
    $entryForm = new EntryForm();
     if ($entryForm->load(Yii::$app->request->post()) && $entryForm->insertFormData()) {
     }

}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douchaqi3369 2017-02-18 11:49
    已采纳

    Why do you redeclare the variables in the database? you're basically telling yii to ignore the attributes on the table.

    public $id;
    public $name;
    public $email;
    public $age;
    public $height;
    public $weight;
    public $city;
    public $checkboxList;
    public $checkboxList1;
    public $imageFiles;
    

    Remove the public declarations and see if it works.

    点赞 打赏 评论
  • duanmao1975 2017-02-16 14:21

    Your code looks ok, so probably you have some validation errors.

    In the insertFormData() method add the following to get the validation errors:

    if (!$entryForm->validate()){
        var_dump($entryForm->getErrors());
    }
    

    Later edit:

    Your insertFormData method is basically useless because the $entryForm->load loads the data from POST. The second problem is probably with the file upload. To get the uploaded files use UploadedFile::getInstance($model, 'imageFile'). More info here

    I suggest you to create a crud using Gii (the crud generator) and then implement the file upload according to the documentation mentioned above. And in this case you will see the validation errors too.

    点赞 打赏 评论

相关推荐 更多相似问题