无法从POST请求中获取数据

时间:2017-02-16 21:23:05

标签: php yii2

我想从POST请求中获取数据。我有创建此POST请求的表单并将其重定向到某个操作,您可以在此行中看到:

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

然后一些方法,在我的情况下,SiteController中的actionForm()必须处理这个请求。 我需要获取该数据并将其保存到db。我有这个模型:

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "form".
 *
 * @property integer $id
 * @property string $name
 * @property string $email
 * @property integer $age
 * @property integer $height
 * @property integer $weight
 * @property string $city
 * @property string $techies
 * @property string $english_level
 * @property resource $photo_1
 * @property resource $photo_2
 * @property resource $photo_3
 * @property resource $photo_4
 * @property resource $photo_5
 */
class Form extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'form';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'email', 'age', 'height', 'weight', 'city', 'techies', 'english_level', 'photo_1', 'photo_2', 'photo_3', 'photo_4', 'photo_5'], 'required'],
            [['name', 'email', 'city', 'techies', 'english_level', 'photo_1', 'photo_2', 'photo_3', 'photo_4', 'photo_5'], 'string'],
            [['age', 'height', 'weight'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'email' => 'Email',
            'age' => 'Age',
            'height' => 'Height',
            'weight' => 'Weight',
            'city' => 'City',
            'techies' => 'Techies',
            'english_level' => 'English Level',
            'photo_1' => 'Photo 1',
            'photo_2' => 'Photo 2',
            'photo_3' => 'Photo 3',
            'photo_4' => 'Photo 4',
            'photo_5' => 'Photo 5',
        ];
    }
}

这是从gii模型生成器创建的模型。我也在我的db命名表单和所有行中有表。在我的db.php中,我有db的所有配置。 但是当我单击表单中的按钮时,页面只会重新加载而不会创建任何内容。 控制器中的操作:

public function actionForm()
{
    $Form = new Form();
    if (($loaded = $Form->load(Yii::$app->request->post('form'))) && $Form->save()) {
                return 'ok';
    }elseif($loaded){
 var_dump($Form->getErrors());
 }

    return $this->render('form',array(
       'Form' => $Form,
    ));
}
when all good that method must to show "ok" or errors,but nothing happened,but something must to happen.

我的观看文件:

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use dosamigos\fileupload\FileUploadUI;
?>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<?php $form = ActiveForm::begin([
        'id' => 'my-form',
        'options' => ['enctype' => 'multipart/form-data'],
        'action' => ['site/form']
    ]); ?>
    <div class="row">
        <div class="col-lg-6">
            <?= $form->field($Form, 'name')->textInput(['class'=>'name_class'])->input('name',['placeholder' => "Имя"])->label(false); ?>
        </div>
        <div class="col-lg-6">
            <?= $form->field($Form, 'email')->textInput()->input('email',['placeholder' => "E-mail"])->label(false); ?>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6">
            <?= $form->field($Form, 'age')->textInput()->input('age',['placeholder' => "Возраст(полных лет)"])->label(false); ?>
        </div>
        <div class="col-lg-6">
            <?= $form->field($Form, 'height')->textInput()->input('height',['placeholder' => "Рост"])->label(false); ?>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6">
            <?= $form->field($Form, 'weight')->textInput()->input('weight',['placeholder' => "Вес"])->label(false); ?>
        </div>
        <div class="col-lg-6">
            <?= $form->field($Form, '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($Form, 'techies')->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($Form, 'english_level')->checkboxList(['starter'=>'Без знания', 'elementary'=>'Базовый', 'intermediate'=>'Средний','up-intermediate'=>'Высокий','advanced'=>'Превосходный'])->label(false) ?>
    </div>
        <script>
        $('#my-form').submit( function(e) {
        e.preventDefault();

        var data = new FormData(this); // <-- 'this' is your form element

        $.ajax({
                url: 'index.php/Form',
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function(data){
                    alert(data);
                },
                error: function(){
            alert('ERROR at PHP side!!');
        }
    });
    });

        </script>
        <script>
        $(function() {
        // Multiple images preview in browser
        var imagesPreview = function(input, placetoinsert) {

            if (input.files) {
                var filesAmount = input.files.length;

                for (i = 0; i < filesAmount; i++) {
                    var reader = new FileReader();

                    reader.onload = function(event) {
                        $($.parseHTML('<img>')).attr('src', event.target.result).appendTo('.preview');
                    }

                    reader.readAsDataURL(input.files[i]);
                }
            }

        };

        $('#gallery-photo-add').on('change', function() {
            imagesPreview(this, 'div.gallery');
        });
    });
    </script>
    <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($Form, 'images[]')->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() ?>

2 个答案:

答案 0 :(得分:0)

在表单操作中,您'action' => ['site/form']创建Url相对于当前controller'site/site/form'而非使用'action' => ['/site/form'],这将解决您的问题或者,如果您的表单由同一action提供,则您只能提供处理表单的控制器controller

答案 1 :(得分:0)

如果您使用的是PHP版本&gt; 5.4,请按以下方式使用

Yii:$app->request->post('form')['name']; //For PHP > 5.4
//or for PHP < 5.4 :
$post =Yii::$app->request->post('UserFormModel');