so I have a form that contains a hidden input.
<?= $this->Form->create(null, [ 'class' => '', 'templates' => 'Inspinia.form_basic']) ?>
<?php
echo $this->Form->control('name');
echo $this->Form->control('description', ['type' => 'text']);
echo $this->Form->control('chart_type', [ 'options' => $this->App->availableCharts() ] );
echo $this->Form->control('frequency', [ 'options' => ['monthly' => 'Monthly','quarterly'=>'Quarterly','snapshot' =>'Snapshot','monthly/quarterly' => 'Monthly/Quarterly'] ] );
echo $this->Form->control('public', [ 'options' => ['1' => 'Public','0' => 'Private'] ] );
// $this->Form->unlockField('deleted');
echo $this->Form->hidden('deleted',['value' => 0]);
?>
<?= $this->Form->button(__('Save'), ['class' => 'btn btn-sm btn-primary pull-right m-t-n-xs']) ?>
<?= $this->Form->end() ?>
Whenever I try to submit the form, it throws me this error
Missing field 'deleted' in POST data
I know I can bypass this by just doing
$this->Form->unlockField('deleted');
but I don't want to bypass the security component in Cakephp, so is there any other way I can get CakePhp to allow me to submit this hidden field?
this is my controller nothing too much but here just in case you guys are wondering
public function test() {
if ($this->request->is('post')) {
debug($this->request->data);
}
}
It should like below
<?php
echo $this->Form->input('nameoffield',array('type'=>'hidden'));
?>
or passing a hidden value
<?php
$hidden_value = 0;
echo $this->Form->input('nameoffield',array('type'=>'hidden','value' => $hidden_value));
?>
Related
how to redirect the users after login,
i tried to use all of these :
Yii::$app->request->getReferrer(); // printing the refferrer url to screen
$this->redirect(\Yii::$app->request->referrer)
return \Yii::$app->getResponse()->redirect(\Yii::$app->getUser()->getReturnUrl($defaultUrl));
none of these above is working
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
$this->goHome();
// $this->goHome();
}
/** #var LoginForm $model */
$model = \Yii::createObject(LoginForm::className());
$event = $this->getFormEvent($model);
$this->performAjaxValidation($model);
$baseurl = \Yii::$app->request->getAbsoluteUrl();
$this->trigger(self::EVENT_BEFORE_LOGIN, $event);
if ($model->load(\Yii::$app->getRequest()->post()) && $model->login()) {
$this->trigger(self::EVENT_AFTER_LOGIN, $event);
// return $this->redirect(\Yii::$app->request->referrer);
// return \Yii::$app->getResponse()->redirect(\Yii::$app->getUser()->getReturnUrl($defaultUrl));
// return \Yii::$app->request->getReferrer(); // printing the refferrer url to screen :(!!
return $this->redirect($baseurl);
// return $this->redirect(\Yii::$app->request->referrer);; //this one is returning everthing to main page, because of line 147
// return $this->goBack();
}
return $this->render('login', [
'model' => $model,
'module' => $this->module,
]);
}
In the web.php config i have this :
$config =[
..//
'modules' => [
'user' => [
'class' => 'dektrium\user\Module',
'enableUnconfirmedLogin' => true,
'confirmWithin' => 21600,
'cost' => 12,
'enableFlashMessages' => true,
'admins' => ['a'],
],
//..
all of these above is just sending the user after login to the home page
what should i do please , i have searched every where read the documentations
After 4 hours of trying i tried to "Echo" the URL after requesting referrer ;
the referrer is working fine the problem is after login the page loads more than one time and here is the problem why it's not sending back to that page but sending people to the current page (login page) then if he is a user he is automatically sending home.
The problem is common and it is related to the issue that at the time when you post login, your actual referrer is login page - actionLogin(), so you are redirected back again and off course you get passed throughout the
condition that you are not the Guest. In order to handle this, you have to assign a referrer to a modal field, so it can be posted with the login information. So at the time when login is validated, you have the required referrer url in your field. Check if you have this field identified in your form:
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?= $form->field($model, 'referer')->hiddenInput()->label(false) ?>
Controller
$form = new LoginForm();
//get previos viewed page url and store in the new model
$form->referer = Yii::$app->request->referrer;
if ($form->load(Yii::$app->request->post())) {
if($form->login()){
return $this->goBack((($form->referer) ? $form->referer : null));
}
}
LoginForm() model
public $referer;
/**
* {#inheritdoc}
*/
public function rules()
{
return [
//...
['referer', 'string'],
];
}
After that, when it will be post request, this field will contain a referrer, which you will pass in your controller.
Further, if you use the yii2-user module, now it is possible and necessary in the config in the controllerMap to remove all forced redirects for the event "after logging in" (I commented them out):
...
'modules' => [
'user' => [
'class' => \dektrium\user\Module::className(),
'admins' => ['adminname'],
'enableConfirmation' => false,
'modelMap' => [
'User' => 'app\models\User',
'UserSearch' => 'app\models\UserSearch',
'Profile' => 'app\models\Profile',
],
'controllerMap' => [
'profile' => 'app\controllers\user\ProfileController',
'security' => [
'class' => \dektrium\user\controllers\SecurityController::className(),
'on ' . \dektrium\user\controllers\SecurityController::EVENT_AFTER_LOGIN => function ($e) {
/*if (Yii::$app->user->can('student free')) {
Yii::$app->response->redirect(array('/course'))->send();
}
if (Yii::$app->user->can('admin')) {
Yii::$app->response->redirect('http://site.ru/user/')->send();
}*/
//Yii::$app->response->redirect(Yii::$app->request->referrer)->send();
// Yii::$app->response->redirect(array('/user/'.Yii::$app->user->id))->send();
//Yii::$app->end();
}
],
],
],
...
I did it, with the help of #serghei Leonenco,
but i had these problems :
The page reloaded after pressing the button submit so the referrer was the login page always and this is why it kept sending users to main page.
I had to get the referrer before the form begin.
I had to pass the value of the referrer to a hidden input.
I had to check if the referrer is from my website or the guest got on login page from a 3rd party site.
Passed the value after checking, used redirect and Url::to('link', true) because the value i got from referrer was a full URL and i couldn't just redirect to a full link this is why i used Url::to with the true condition which means creating a new URL.
View
Notice that i used the referrer value before the form.
<div class="panel-body arab">
**<?php $referer = \Yii::$app->request->referrer;?>**
<?php $form = ActiveForm::begin([
'id' => 'login-form',
'enableAjaxValidation' => true,
'enableClientValidation' => false,
'validateOnBlur' => false,
'validateOnType' => false,
'validateOnChange' => false,
]) ?>
**<?= $form->field($model, 'referer')->hiddenInput(['value' => $referer])->label(false) ?>**
<?php if ($module->debug): ?>
<?= $form->field($model, 'login', [
'inputOptions' => [
'autofocus' => 'autofocus',
'class' => 'form-control',
'tabindex' => '1']])->dropDownList(LoginForm::loginList());
?>
<?php else: ?>
<?= $form->field($model, 'login',
['inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control', 'tabindex' => '1']]
);
?>
<?php endif ?>
<?php if ($module->debug): ?>
<div class="alert alert-warning">
<?= Yii::t('user', 'Password is not necessary because the module is in DEBUG mode.'); ?>
</div>
<?php else: ?>
<?= $form->field(
$model,
'password',
['inputOptions' => ['class' => 'form-control', 'tabindex' => '2']])
->passwordInput()
->label(
Yii::t('user', 'Password')
. ($module->enablePasswordRecovery ?
' (' . Html::a(
Yii::t('user', 'Forgot password?'),
['/user/recovery/request'],
['tabindex' => '5']
)
. ')' : '')
) ?>
<?php endif ?>
<?= $form->field($model, 'rememberMe')->checkbox(['tabindex' => '3']) ?>
<?= Html::submitButton(
Yii::t('user', 'Sign in'),
['class' => 'btn btn-success btn-block', 'tabindex' => '4']
) ?>
<?php ActiveForm::end(); ?>
Model
Notice I used regex to make sure that the user got to login page using my website.
public function getReferer()
{
$getLink = \Yii::$app->request->post('login-form')['referer'];
if(preg_match('/tajrobtak/', $getLink)){
return $getLink;
} else {
return "";
}
}
Controller
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
$this->goHome();
}
/** #var LoginForm $model */
$model = \Yii::createObject(LoginForm::className());
$referery = $model->getReferer();
$event = $this->getFormEvent($model);
$this->performAjaxValidation($model);
$this->trigger(self::EVENT_BEFORE_LOGIN, $event);
if ($model->load(\Yii::$app->getRequest()->post()) && $model->login()) {
$this->trigger(self::EVENT_AFTER_LOGIN, $event);
$this->redirect(Url::to($referery,true));
}
return $this->render('login', [
'model' => $model,
'module' => $this->module,
]);
}
I have data that is being passed through an POST method. However when I try to get some data out of it and set it to a session variable, there is no data in it yet when I print_R($_POST) I see there is Data in it.
This is What I'm getting when I print_r() the POST data.
Array (
[_csrf] => nXRvIHfHWeao64YBdwcdFJa3fz-KShIyAuHDNtKQqhCkDRdwErUqkOrSyHQQamtR5cBHWc57QUNq16hflaftKQ==
[LoginForm] => Array (
[compayname] =>Termite Soup
[username] => Jim.Bot
[password] => 123456
[url] =>
)
[login-button] =>
)
This is what I've tried.
This is the form where form is being filled.
<?php $form = ActiveForm::begin([
'id' => 'login-form',
'layout' => 'horizontal',
'fieldConfig' => [
'template' => "{label}\n<div class=\"col-lg-10\">{input}
</div>\n<div class=\"col-lg-8\">{error}</div>",
'labelOptions' => ['class' => 'col-lg-3 control-label'],
],
]);
?>
<?php echo $form->field($model,
'compayname')>dropDownList(['GF_TB_TNT' => 'GF-TNT',
'Chicken Soup' =>'Dog Soup',
'Termite Soup' =>'Termite Soup',
],
['prompt'=>'Select Company']); ?>
<?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'url')->hiddenInput()->label(''); ?>
<div class="row">
<div class="btn-group">
<!-- <div class="col-md-2">
</div> -->
<div class="col-md-6">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary pull-left', 'name' => 'login-button','style'=>'font-size: 15px;']) ?>
</div>
Getting the data and setting it to a Session Variable
if (Yii::$app->request->post()) {
$companyname = Yii::$app->request->post('compayname');
}
I want to set the companyname in the POST to a session Variable
What you can do is
foreach (Yii::$app->request->post('LoginForm') as $field) {
// some logic
}
Also I see a mistake in compayname. A "n" is missing in the word. But you can access it's value by Yii::$app->request->post('LoginForm')['compayname'];
You can shortly get this.
$arr = [];
foreach ($_POST as $param) {
if (is_array($param)) {
foreach ($param as $name) {
if ($name == 'LoginForm') {
array_push($arr, $name);
}
}
} else {
}
}
And you can figure out how the data is structured using var_dump
var_dump($arr);
I have this kind of problem. I have an input text that have template of radio in it.
the problem is that I want to get the value of that radio when I check it and store it to the database field.
my idea is to create a variable from model but i can't pass the radio value to that variable when i save it.
please help me I am stuck with it.
here is the images of view:
Controller action:
public function actionCreate()
{
$model = new QbQuestion();
if ($model->load(Yii::$app->request->post())) {
$answer = $model->answer;
$model->$answer;
$model->save();
return $this->redirect(Url::to(['qb-question/index']));
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
View:
<div class="qb-question-form">
<?php $form = ActiveForm::begin([
'layout' => 'horizontal',
'fieldConfig' => [
'horizontalCssClasses' => [
'label' => 'col-sm-4',
'offset' => 'col-sm-offset-4',
'wrapper' => 'col-sm-8',
'button' => 'col-sm-8',
'error' => '',
'hint' => '',
],
],
]); ?>
<?php echo $form->errorSummary($model); ?>
<?= $form->field($model, 'q_cat')->dropDownList(
ArrayHelper::map(QbCategory::find()->all(), 'id', 'category'),
[
'prompt' => 'Select Category'
]) ?>
<?= $form->field($model, 'q_date')->dropDownList(
ArrayHelper::map(QbDate::find()->asArray()->all(), 'id',
function($model, $defaultValue) {
return $model['month'].' '.$model['year'];
}),
[
'prompt' => 'Select Date'
]) ?>
<?php echo $form->field($model, 'question')->textarea(['rows' => 5]) ?>
<?= $form->field($model, 'q_c1', [
'inputTemplate' => '<div class="input-group"><span class="input-group-addon">'.
Html::radio('answer').'</span>{input}</div>',
]); ?>
<?= $form->field($model, 'q_c2', [
'inputTemplate' => '<div class="input-group"><span class="input-group-addon">'.
Html::radio('answer').'</span>{input}</div>',
]); ?>
<?= $form->field($model, 'q_c3', [
'inputTemplate' => '<div class="input-group"><span class="input-group-addon">'.
Html::radio('answer').'</span>{input}</div>',
]); ?>
<?= $form->field($model, 'q_c4', [
'inputTemplate' => '<div class="input-group"><span class="input-group-addon">'.
Html::radio('answer').'</span>{input}</div>',
]); ?>
<?php echo Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
</div>
thanks in advance.
radio field that you have take will always return 1, So you can't identify selected answer. You can do it normal html as below:
Change in Your Form file :
<?= $form->field($model, 'q_c1', [
'inputTemplate' => '<div class="input-group"><span class="input-group-addon">'.
'<input type="radio" name="QbQuestion[answer]" value="q_c1">'.'</span>{input}</div>',
]); ?>
<?= $form->field($model, 'q_c2', [
'inputTemplate' => '<div class="input-group"><span class="input-group-addon">'.
'<input type="radio" name="QbQuestion[answer]" value="q_c2">'.'</span>{input}</div>',
]); ?>
<?= $form->field($model, 'q_c3', [
'inputTemplate' => '<div class="input-group"><span class="input-group-addon">'.
'<input type="radio" name="QbQuestion[answer]" value="q_c3">'.'</span>{input}</div>',
]); ?>
<?= $form->field($model, 'q_c4', [
'inputTemplate' => '<div class="input-group"><span class="input-group-addon">'.
'<input type="radio" name="QbQuestion[answer]" value="q_c4">'.'</span>{input}</div>',
]); ?>
Here ,QbQuestion['answer'] return you the selected answer.
Change in controller:
public function actionCreate()
{
$model = new QbQuestion();
if ($model->load(Yii::$app->request->post())) {
// if you have answer attribute in model class than load that attribute
// no need of this line $answer = $model->answer;
// no need of this line $model->$answer;
// you can do it manually as below
$model->answer=$_REQEST['QbQuestion']['answer'];
$model->save();
return $this->redirect(Url::to(['qb-question/index']));
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
The reason your attributes are not saving is because you haven't tied the field to the model, so incorrect field names are being submitted in the form.
It seems to me as if what you need is a radioList. The Html::radio() method just adds a radio button, not tied to any model. To use a radioList you need to do something like this;
First, create an array of possible answers in your view file;
$answers = array('q_c1' => $model->q_c1, 'q_c2' => $model=>q_c2, 'q_c3' => $model=>q_c3, 'q_c4' => $model=>q_c4);
Now, because it's a radio list, it will only submit data for one of the radio button. It will not allow selection of more than one radio button. Because of the way you are storing your data, you will need a temporary model attribute to store this value oin while the model gets populated and validated. Create this in your model like so;
public $answerToQuestion;
And allow it to be massively assigned;
public function rules() {
return [
[['answerToQuestion'], 'safe]
];
}
Now you can create your form field like this;
echo $form->field($model, 'answerToQuestion')->radioList($answers);
Yii should now generate the list of radio buttons with the correct names to tie them into your model and allow them to be massively assigned.
The attributes submitted by the form will be of the form (assuming your model is called Question;
Question[answerToQuestion] => 'q_c2'
It will pass validation. It's now up to your model logic to decode the selected answer into the relevant fields in your database.
I am getting this error in CakePHP from my forgot_password method which is in UsersController.
public function forgot_password() {
$this->layout = 'signin';
if (!empty($this->data)) {
$user = $this->User->findByUsername($this->data['User']['username']);
if (empty($user)) {
$this->Session->setflash('Sorry, the username entered was not found.');
$this->redirect('/users/forgot_password');
}else{
$user = $this->__generatePasswordToken($user);
if ($this->User->save($user) && $this->__sendForgotPasswordEmail($user['User']['id'])) {
$this->Session->setflash('Password reset instructions have been sent to your email address.
You have 24 hours to complete the request.');
$this->redirect('/users/login');
}
}
}
}
Here is the forgot_password.ctp file
<header class="panel-heading text-center">
<strong>Forget Password</strong>
</header>
<h3>Enter Your Username</h3>
<?php
echo $this->Form->create('User', array('action' => 'forgot_password', 'id' => 'web-form', 'class'=>'panel-body wrapper-lg'));
echo $this->Form->input('username', array('label' => 'Username', 'between'=>'<br />', 'type'=>'text', 'div' => 'form-group','class' => 'form-control input-lg'));
?>
<div class="form-group">
<?php echo $this->Form->submit('Send Password Reset Instructions', array('class' => 'btn btn-primary btn-techuz', 'id' => 'submit')); ?>
</div>
<?php echo $this->Form->end(); ?>
It's not necessary to specify the form action if it's same as the view. In case you'd like to redirect to a different action, try this:
<?php
echo $this->Form->create('User', array(
'url' => array(
'controller' => 'users','action' => 'forgot_password'
),
'id' => 'web-form',
'class' =>'panel-body wrapper-lg'
)
); ?>
If you follow the convention and define this "url" index as an array of controller and index, you're bound to be safe and deprived of errors.
Peace! xD
Got the solution, no need to mention 'action' => 'forgot_password' in forgot_password.ctp file until it is redirect to another method.
I was trying to validate my YII2 change password form. But I'm stuck on YII2 on blur validation.
<?php
use yii\bootstrap\ActiveForm;
use yii\helpers\Html;
?>
<?php
$form = ActiveForm::begin([
'id' => 'change-password',
'action' => $action,
'enableAjaxValidation' => true
]);
?>
<?php echo $form->field($model, 'old_password')->label(false)->passwordInput(['placeholder' => 'Your Old Password', 'class' => 'form-control']); ?>
<?php echo $form->field($model, 'new_password')->label(false)->passwordInput(['placeholder' => 'Your New Password', 'class' => 'form-control']); ?>
<?php echo $form->field($model, 'confirm_password')->label(false)->passwordInput(['placeholder' => 'Confirm Your New Password', 'class' => 'form-control']); ?>
<?php echo Html::submitButton('Submit', array('class' => 'btn btn-primary')); ?>
<?php ActiveForm::end(); ?>
Can anyone let me know what wrong I am doing?
It's not enough to just include it in ActiveForm config.
The requests can be sended but the form will stay unchanged.
You should also prepare your controllers (in CRUD generated controllers they are create and update, in your case it can be just one - which is responsible for updating password) to return proper JSON data in case of AJAX request.
See how it's done in official documentation.
Model class Scenario function must have a default option:
public function scenarios()
{
return [
'default' => ['old_password', 'new_password', 'confirm_password']
];
}