【发布时间】:2017-05-02 22:24:15
【问题描述】:
我有两个模型 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 表单数据..
【问题讨论】:
-
更新您添加相关模型、控制器/动作和视图代码的问题..
-
能否请您交叉检查请求是否是使用 print_r(Yii::$app->request->isAjax) 调用的 Ajax;出口();你必须得到真实的。
-
将此代码放入模型 B 的 actionsCreate() 中。
-
您也可以在表单中添加 id,例如 $form = ActiveForm::begin([ 'id' => 'activity-form' ]);
-
您好 Ankur,感谢您的回复。更新了还是不行,还是一样的问题