Yii2: How to access _POST method data - php

Sending form data from one action to another
<?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(); ?>
index page has the above form from which sending data to 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,
]);
}
How to display arrival and departure in roomsearch page?
Created model using \yii\base\DynamicModel

Well as you are redirecting from one action to another , you cant access POST data in the second action. But you can pass it as get parameters
return $this->redirect(\yii\helpers\Url::to([
'/you_controller/your_action',
'arrival' => $arrival ,
'departure' => $departure
]));
In your Second Action
$arrival = yii::$app->request->get('arrival');
$departure = yii::$app->request->get('departure');

Used dynamic model as no data need to save in database
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]);
}
To get the POST method data in actionRoomsearch
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]);
}
To display data on page <?php echo $arrival; ?>

Since this is a communication between two request. I will prefer to use Flash
Note: Flash will be deleted automatically after the next request.
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]);
}
In the room-search page
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
}
The reason I prefer this method over $_GET is because there are times
where you have to send security sensitive data over pages and you don't
want it revealed in the browser's address bar.
E.g ID that is posted in an hidden field.

Related

yii2 ajax validation error in widget, yii\web\Response

I'm getting error from yii\web\Response when I use ajax validation.
Object of class yii\web\Response could not be converted to string
widget:
public function run()
{
$model = new Participants();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post())) {
$list = implode( ", ",$model->sections);
$model->sections = $list;
$model->save();
Yii::$app->session->setFlash(Alert::TYPE_SUCCESS, [
[
'title' => 'Congratulations!',
'text' => 'You are registered on the forum. Check out your email to get news about forum.',
'confirmButtonText' => 'Done!',
]
]);
return Yii::$app->controller->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl);
}
return $this->render('header', [
'model' => $model,
]);
}
view of widget:
<?php $form = ActiveForm::begin();?>
...
<?= $form->field($model, 'email', ['enableAjaxValidation' => true])->textInput(['placeholder' => 'Email']); ?>
how I can solve this error? P.S. yii version - 2.0.17-dev
\yii\base\Widget::run() must return a string (all widgets basically)
All you should do within method run() is output or render content and you're attempting to return a Response object by way of return ActiveForm::validate($model); and return Yii::$app->controller->redirect(..)
i suggest you move all the code that supposed to handle form submission to it's own action
SiteController extends controller {
public function actionRegisterParticipant {
$model = new Participants();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post())) {
$list = implode(", ", $model->sections);
$model->sections = $list;
$model->save();
Yii::$app->session->setFlash(Alert::TYPE_SUCCESS, [
[
'title' => 'Congratulations!',
'text' => 'You are registered on the forum. Check out your email to get news about forum.',
'confirmButtonText' => 'Done!',
]
]);
return Yii::$app->controller->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl);
}
// ...
}
and the form in the widget view should always point to this action:
<?php $form = ActiveForm::begin(['action' => 'site/register-participant']);?>
...
<?= $form->field($model, 'email', ['enableAjaxValidation' => true])->textInput(['placeholder' => 'Email']); ?>
Widget should return string as a result, but return Yii::$app->controller->redirect() returns Response object with configured redirection. If you want to redirect inside of widget you should use something like that:
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->controller->asJson(ActiveForm::validate($model));
Yii::$app->end();
}
// ...
Yii::$app->session->setFlash(/* ... */);
Yii::$app->controller->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl);
Yii::$app->end();
But this smells like a bad design - widget should not be responsible for controlling application flow. It is better to handle user input in regular action/controller.

yii2 conditional validation on server side

I have one form that form have below fields
i)Book
ii)Amount
Controller action:
public function actionBook()
{
$model = new Book();
if ($model->load(Yii::$app->request->post()) && $model->validate()){
print_r($model);exit;
return $this->redirect('/Book');
}
$model->getBook();
return $this->render('BookForm', ['model' => $model]);
}
Whenever this page will load i will call one model function by default, the function is getBook()
Model:
public book;
public amount;
public showAmountField;
public function rules()
{
return [
[['book'], 'required'],
['amount', 'required', 'when' => function($model) {
return $model->showAmountField == true;
}],
];
}
public function getBook()
{
if(some condition here){
$this->showAmountField = true;
}
}
so whenever the showAmountField is true at the time the amount field is required, otherwise it will not required, here all are working fine and the client side validation also working fine, but when i change amount field id using console(f12) at the time the server side validation not working and form is simply submit with the amount field is empty, so what is wrong here. Please explain anyone.
UPDATE
View
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
$this->params['breadcrumb'] = $model->breadCrumbs;
?>
<?php $form = ActiveForm::begin([
'id' => 'book-form',
'options' => ['class' => 'form-horizontal'],
]);
?>
<?= $form->field($model, 'book')->textInput()->label("Book"); ?>
<?php if($model->showAmountField): ?>
<?= $form->field($model, 'amount')->textInput()->label("Amount"); ?>
<?php endif; ?>
<?= $form->errorSummary($model, ['header' => '']); ?>
<?php ActiveForm::end(); ?>
Validation occurs on the field ID, if you change it through the console, the model does not understand that it needs to validate
$model = new Book();
if ($model->load(Yii::$app->request->post()) && $model->validate()){
print_r($model);exit;
return $this->redirect('/Book');
}
$model->getBook();
here you are initialising the $model->getBook(); after the if block so the model gets overridden in post request with new instance and hence server side validations fails for when condition.
$model = new Book();
$model->getBook();
if ($model->load(Yii::$app->request->post()) && $model->validate()){
print_r($model);exit;
return $this->redirect('/Book');
}
it should be before post load

Displaying the fields of tables three times and saving the value uniquely

I have a problem when it comes to saving the fields of tables being displayed three times. Cant save the unique value being saved in the text fields. Kindly someone direct me to the right answer please.
View code :
<h2>List of Documents</h2>
<table class="table">
<?php foreach($formlist as $item) { ?>
<tr>
<td><?= $form->field($model, '['.$item->id.']value')->radioList(['yes'=>' yes','no'=>' no'])->label($item['title']); ?></td>
</tr>
<?php } ?>
</table>
Controller code :
public function actionCreate()
{
$model = new Form();
$forminfo = new Forminfo();
$forminfo->id = $model->forminfo_id;
/*$sql = 'SELECT * FROM formlist ORDER BY id ASC';
$db = Yii::$app->db;
$formlist = $db->createCommand($sql)->queryAll();*/
// same of ->
$formlist = Formlist::find()->orderBy(['id'=>SORT_ASC])->all();
if ($forminfo->load(Yii::$app->request->post()) && $model->load(Yii::$app->request->post())) {
$forminfo->save(false); // skip validation as model is already validated
$model->forminfo_id = $forminfo->id; // no need for validation rule on user_id as you set it yourself
$model->save(false);
Yii::$app->getSession()->setFlash('success', 'You have successfully saved your data.');
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'forminfo' => $forminfo,
'formlist' => $formlist,
]);
}
}
For accessing tabular input you should use loadMultiple('yourModel')
or a loop on
$post= Yii::$app->request->post());
foreach ($post['your_model'] as $key => $myModel) {
// $myModel contain the current model
}
this yii2 guide could be useful http://www.yiiframework.com/doc-2.0/guide-input-tabular-input.html

How can I pass parameter/dropdown value to model function

I am using yii2 advanced template improved
Not sure if relevant to problem/a solution but to get to the category I have a form with some javascript which on change redirects the user to the category selected.
I have the following code which allows me to access the posts within that category id I go to localhost:8888/advanced/article/category?id=1
The problem at the minute is that if I call getCategoryName function in my model from my category view the id parameter isn't being passed to the model function therefore when using getCategoryName defaults to sport.
public function actionCategory($id)
{
$model = new Article();
$searchModel = new ArticleSearch();
$query = Article::find()
->where(['category' => $id]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
return $this->render('category', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model'=>$model,
]);
}
Then within my view I use the following which works to an extent in terms of executing the model function, however I am unsure on how to pass the parameter/current category id to the model function. The below code work for the _index & in the single article view.
<?= $model->CategoryName ?>
This is my model function
public function getCategoryName($category = null)
{
$category = (empty($category)) ? $this->category : $category ;
if ($category === self::CATEGORY_ECONOMY)
{
return Yii::t('app', 'Economy');
}
elseif ($category === self::CATEGORY_SOCIETY)
{
return Yii::t('app', 'Society');
}
else
{
return Yii::t('app', 'Sport');
}
}
Use something like this, in your view
$request = Yii::$app->request;
$id = $request->get('id');//get id from request or change according to your requirement
echo $model->getCategoryName($id);//full method name here
Try to use this. change === to ==:
public function getCategoryName($category = null)
{
$category = (empty($category)) ? $this->category : $category ;
if ($category == self::CATEGORY_ECONOMY)
{
return Yii::t('app', 'Economy');
}
elseif ($category == self::CATEGORY_SOCIETY)
{
return Yii::t('app', 'Society');
}
else
{
return Yii::t('app', 'Sport');
}
}

Laravel 4.2 session::get() method not returning session data in controllers

Hi help me,
login code
public function store()
{
$credentials = array(
'u_email' => Input::get('email'),
'password' => Input::get('password'));
if (Auth::attempt($credentials) ) {
$user = Auth::user()->toArray();
$userrole = with(new User)->get_user_role($user['u_id']);
$userobj['u_id'] = $user['u_id'];
$userobj['u_shortcode'] = $user['u_shortcode'];
$userobj['utype'] = $user['utype'];
$userobj['u_title'] = $user['u_title'];
$userobj['u_fname'] = $user['u_fname'];
$userobj['u_lname'] = $user['u_lname'];
$userobj['u_email'] = $user['u_email'];
$userobj['u_role'] = $userrole;
$userobj['id'] = Session::getId();
Session::put('admin', $userobj);
$value = Session::get('admin');
return Response::json([
'user' => $userobj ],
202
);
}else{
return Response::json([
'flash2' => 'Authentication failed'],
202
);
}
}
and my second controller is:
public function get_sessionobj()
{
var_dump(Session::all());
$value = Session::get('admin');
print_r($value);
exit();
}
when i am calling second controller after login then session data not printed. in login controller Session::get('admin') function returning data. and i am using file driver for session storage. I have seen my session file there was some data like this:
a:5:{s:6:"_token";s:40:"XrUgs7QLPlXvjvyzFaTdmDpqGL0aSZRzkJS0il9f";s:38:"login_82e5d2c56bdd0811318f0cf078b78bfc";s:1:"1";s:5:"admin";a:9:{s:4:"u_id";s:1:"1";s:11:"u_shortcode";s:5:"u1001";s:5:"utype";s:1:"1";s:7:"u_title";s:3:"Mr.";s:7:"u_fname";s:6:"Aristo";s:7:"u_lname";s:5:"Singh";s:7:"u_email";s:24:"chandan.singh#jetwave.in";s:6:"u_role";a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}s:2:"id";s:40:"cd074f7f61fcc88b3d92c482e57e8a12dc888958";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1410525787;s:1:"c";i:1410525787;s:1:"l";s:1:"0";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
Call a function get_sessionobj() in store function
Example:
public function store(){
$this->get_sessionobj();
}

Categories