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']
];
}
Related
I have a quick question. I implemented a dropdownList in a _form.php. Now my action crate won't work properly anymore. I am not sure if there is an issue with me sending the request to the action. But it's not really doing the trick anymore.
With the $form->field($model, 'team_idteam')->textInput() it worked just fine. So, this is what I have so far on the _form.php:
<div class="user-has-team-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'team_idteam')->textInput() //<-- This works perfectly. ?>
<?= $form->field($model, 'teamIdteam')->dropDownList(ArrayHelper::map(Team::find()->all(), 'idteam', 'name')) <-- This does not work at all ?>
<?= $form->field($model, 'user_iduser')->textInput() ?>
<?= $form->field($model, 'oncallduty')->checkbox() ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
My actionCreate looks like this:
public function actionCreate()
{
$model = new UserHasTeam();
if ($this->request->isPost) {
Yii::info("Test1"); // <-- It get's up to this point.
if ($model->load($this->request->post()) && $model->save()) {
Yii::info("Test2");
return $this->redirect(['view', 'team_idteam' => $model->team_idteam, 'user_iduser' => $model->user_iduser]);
}
} else {
$model->loadDefaultValues();
}
return $this->render('create', [
'model' => $model,
]);
}
The visuals work perfect and I can even chose different teams. If I create new teams, or delete old ones, they are shown or not shown as well. I have to admit I am a bit lost here.
EDIT
I dumped the $_POST array after the $model = new UserHasTeam(); and it gave out the following array:
[
'_csrf' => '0rkl0EAuFwjy9kdJNVQfVTQOkT22Kzo8bdvLAg2X0P_i0Ui-DEAkQ6WxfzsEAkwfBE_1UvNCDlsEjLtOefXmyA==',
'UserHasTeam' => [
'teamIdteam' => '3',
'user_iduser' => '1',
'oncallduty' => '0',
],
]
Yep. I am quite an idiot every now and then.
This is how I solved it:
<?= $form->field($model, 'team_idteam')->dropDownList(ArrayHelper::map(Team::find()->all(), 'idteam', 'name')) ?>
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));
?>
In frontend of Yii ,
I have 2 form :
1 Login Form
2 Signup
my signup form is working , but when login is not working ,
i found a error
Call to a member function formName() on null
//Form Code
<!-------signup---------->
<h1>Signup Form</h1>
<?php $form = ActiveForm::begin(['id' => 'form-signup', 'action' => Url::to(['site/signup'])]); ?>
<?= $form->field($modelSignup, 'username')->textInput(['autofocus' => true]) ?>
<?= $form->field($modelSignup, 'email') ?>
<?= $form->field($modelSignup, 'password')->passwordInput() ?>
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
<?php ActiveForm::end(); ?>
<!-------// signup---------->
<!-------login---------->
<h1>Login Form</h1>
<?php $form = ActiveForm::begin(['id' => 'form-login', 'action' => Url::to(['site/login'])]); ?>
<?= $form->field($modelLogin, 'username')->textInput(['autofocus' => true]) ?>
<?= $form->field($modelLogin, 'email') ?>
<?= $form->field($modelLogin, 'password')->passwordInput() ?>
<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
<?php ActiveForm::end(); ?>
<!-------//login---------->
Try this:
Controller:
public function actionIndex() {
$modelSignup = new SignupForm();
$modelLogin = new LoginForm();
return $this->render('index',[ 'modelSignup' => $modelSignup,'modelLogin' => $modelLogin ]);
}
Also remove this check from your code:
if(isset($modelLogin)
In your view file you are using two models, one for signup and the other for login. But from your comment I had note that you are passing only one model at a time it may be the first one or the second one. So you should replace your actionIndex() with the following code:
public function actionIndex() {
$modelSignup = new SignupForm();
$modelLogin = new LoginForm();
if(isset($_POST['SignupForm'])) {
//code for signup process
}
if(isset($_POST['LoginForm'])) {
//code for login process
}
return $this->render('index', [ 'modelSignup' => $modelSignup, 'modelLogin' => $modelLogin ]);
}
This will help you.
In my application i've a model called User Where i've implemented a scenario for validations.
const SCENARIO_RESET_PASSWORD = 'passwordReset';
public function rules()
{
return[
[['name','surname','password','username','id_role'], 'required'],
[['email','email2'], 'email'],
[['username','email'], 'unique'],
['confirmPassword', 'compare', 'compareAttribute'=>'password', 'on' => self::SCENARIO_RESET_PASSWORD]
];
}
With this configuration i can create a new User, delete one and update all fields except for 'password'.
This is the action in my controller:
public function actionUpdate($id)
{
$user = User::findOne($id);
if($user->load(Yii::$app->request->post())&& $user->validate()) {
$user->update();
$this->redirect(\yii\helpers\Url::toRoute('index'));
}
return $this->render('update',[
'user' => $user,
]);
}
i've already checked that the field 'password' is passed on post parameters with success.
and this is my view:
<h1> Edit User </h1>
<?php
$form = ActiveForm::begin([
'id' => 'active-form',
'options' => [
'class' => 'form-horizontal',
'enctype' => 'multipart/form-data'
],
]);
?>
<?= $form->errorSummary($user); ?>
<?= $form->field($user, 'name') ?>
<?= $form->field($user, 'surname') ?>
<?= $form->field($user, 'username') ?>
<?= $form->field($user, 'email') ?>
<?= $form->field($user, 'password')->passwordInput() ?>
<?php if(Yii::$app->user->identity->id_role === User::USER_ADMIN): ?>
<?= $form->field($user, 'id_role')->dropDownList(
Role::find()->select(['name','id'])->indexBy('id')->column(),
['prompt'=>'Select a role']
);
?>
<?php endif; ?>
<div class="form-group">
<?= Html::submitButton('Save the user', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
I really don't know why i'm getting this error
Please remove
'on' => self::SCENARIO_RESET_PASSWORD
or
define your SCENARIO in your controller action as
$user->scenario = 'SCENARIO_RESET_PASSWORD';
I need to make a search-form in the front-end to take input from users and search for it in the database, then display the data depending on that keyword.
I need to use yii2 active form not HTML form.
If any code example for the search-form, the action in site controller, and the view, it would be grate.
Thanks
Here is the basic one :)
SiteController.php (controller file):
use yii\data\ActiveDataProvider;
use Yii;
class SiteController extends yii\web\Controller
{
public function actionSearch() {
$searchString = Yii::$app->request->get('query');
$searchQuery = Product::find()->where(['name' => $searchString])->orderBy(['ts' => SORT_DESC]);
$productDataProvider = new ActiveDataProvider(['query' => $searchQuery]);
return $this->render('search', compact('productDataProvider'));
}
search.php (view file):
<?php
use yii\helpers\Url;
use yii\grid\GridView;
$form = \yii\widgets\ActiveForm::begin([
'options' => ['role' => 'form', 'method' => 'GET', 'action' => Url::to(['site/search'])]
]); ?>
<?=$form->field($model, 'query')?>
<?=\yii\helpers\Html::submitButton('Поиск')?>
<?php $form->end()?>
<? if ($productDataProvider->totalCount): ?>
<?= GridView::widget([
'dataProvider' => $productDataProvider,
'columns' => [
'id',
'name'
],
]) ?>
<? else: ?>
<p>Ничего не найдено</p>
<? endif; ?>