将表格数据从一个动作发送到另一个动作
<?php $form = ActiveForm::begin(['action' =>'site/roomsearch','method' => 'post']); ?>
<?= $form->field($model, 'arrival')->label(false) ?>
<?= $form->field($model, 'departure')->label(false) ?>
<?= Html::submitButton('Send', ['class' => 'btn btn-white']) ?>
<?php ActiveForm::end(); ?>
索引页面具有上述形式,可以将数据发送到actionRoomsearch()
的actionIndex():
public function actionIndex()
{
$model = new \yii\base\DynamicModel(['arrival','departure','adult','child']);
if($model->load(Yii::$app->request->post()))
{
$arrival = $model->arrival;
$departure = $model->departure;
return $this->redirect([
'roomsearch',
'arrival' => $arrival ,
'departure' => $departure
]);
}
return $this->render('index', ['model'=>$model]);
}
actionroomsearch():
{
$post = Yii::$app->request->post();
$arrival = $post['arrival'];
$departure = $post['departure'];
return $this->render('roomsearch',[
'arrival' =>$arrival,
'departure' => $departure,
]);
}
如何在arrival
页面中显示departure
和roomsearch
?
使用\yii\base\DynamicModel
答案 0 :(得分:2)
当您从一个操作重定向到另一个操作时,您无法在第二个操作中访问POST数据。但您可以将其作为获取参数传递
return $this->redirect(\yii\helpers\Url::to([
'/you_controller/your_action',
'arrival' => $arrival ,
'departure' => $departure
]));
在你的第二次行动中
$arrival = yii::$app->request->get('arrival');
$departure = yii::$app->request->get('departure');
答案 1 :(得分:0)
使用动态模型,因为没有数据需要保存在数据库中
public function actionIndex()
{
$model = new \yii\base\DynamicModel(['arrival','departure']);
$model->addRule(['arrival', 'departure'], 'string', ['max' => 128]);
$arrival = $model->arrival;
if($model->load(Yii::$app->request->post()))
{
$arrival = $model->arrival;
$departure = $model->departure;
$model->save();
}
return $this->render('index', ['model'=>$model]);
}
在actionRoomsearch中获取POST方法数据
public function actionRoomsearch()
{
$data = yii::$app->request->post();
if(isset($data['DynamicModel']))
{
$arrival = $data['DynamicModel']['arrival'];
$departure = $data['DynamicModel']['departure'];
}
return $this->render('roomsearch',['arrival' =>$arrival,'departure' => $departure]);
}
在第<?php echo $arrival; ?>
页上显示数据
答案 2 :(得分:0)
由于这是两个请求之间的通信。我更喜欢使用Flash
注意:下次请求后,Flash会自动删除。
public function actionIndex()
{
$model = new \yii\base\DynamicModel(['arrival', 'departure', 'adult', 'child']);
if($model->load(Yii::$app->request->post()))
{
Yii::$app->session->setFlash('arrival', $model->arrival);
Yii::$app->session->setFlash('departure', $model->departure);
return $this->redirect(['roomsearch']);
}
return $this->render('index', ['model'=>$model]);
}
在房间搜索页面
public function actionRoomSearch()
{
$session = Yii::$app->session;
$arrival = $session->hasFlash('arrival') ? $session->getFlash('arrival') : null;
$departure = $session->hasFlash('departure') ? $session->getFlash('departure') :null;
//Do whatever you like with the data
}
我更喜欢这种方法而不是$ _GET的原因是因为有时候 您必须在页面上发送安全敏感数据,而不是 希望它在浏览器的地址栏中显示出来。 E.g在隐藏字段中发布的ID。