yii2通过发布数据中缺少renderAjax来附加数据

时间:2016-12-17 06:27:25

标签: php ajax yii2 append

我有两个模型A和B,在模型A表单中动态附加模型B,但是当我点击创建按钮时,我没有在POST中获取模型B数据。我在做错了请帮助..

模型A表格(视图)

       <?php
        use yii\helpers\Html;
        use yii\widgets\ActiveForm;
        use yii\helpers\Url;
        use yii\web\View;
        $script = <<< JS

        $.ajax({
        type     :'POST',            
        data: {total_form:1},
        cache    : true,
        url  : '/stag_str/web/index.php/activities/create',
        success  : function(data) {
        $('.p_scents').append(data);
        },
        });

        JS;
        $this->registerJs($script);
        ?>

        <div class="currency-form">

        <?php $form = ActiveForm::begin(); ?>

        <?= $form->field($model, 'currency_name')->textInput(['maxlength' => true,'style'=>'width:150px']) ?>
        <div class="p_scents"></div>
        <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
        </div>

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

        </div>

模型A控制器

      public function actionCreate(){
        $model = new Currency();

        if ($model->load(Yii::$app->request->post())) {
        print_r($_POST);exit;
        return $this->redirect(['view', 'id' => $model->currency_id]);
        } else {
        return $this->render('create', [
        'model' => $model,
        ]);
        }
      }

我通过Ajax调用呈现的模型B表单

            <?php

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

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

        <div class="activities-form">

         <?php $form = ActiveForm::begin(['id' => 'activity' ]); ?>

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

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

        </div>

使用renderAjax的模型B动作

            public function actionCreate()
        {
            $model = new Activities();

            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->activity_id]);
        } elseif ( Yii::$app->request->isAjax ){
           return $this->renderAjax('_form', [
                'model' => $model,
           ]);
        }

        }

我在保存模型表单A时没有获得模型B表单数据。

1 个答案:

答案 0 :(得分:0)

理想情况下,当您从View处理AJAX调用时。您必须在表单中提供ID,如下所示;

$form = ActiveForm::begin([ 'id' => 'activity-form' ]); 

当您在控制器内处理任何类型的请求时,您必须首先检查重新呈现表单时的请求类型,如下所示

elseif ( Yii::$app->request->isAjax ){
   return $this->renderAjax('_form', [
        'model' => $model,
   ]);
}