tips : username and email is check by ajaxValidation with validate method.
all is correct but i guess captcha is changed in server but the old picture is in client.
i googling alot no result found.
this is view:
<?php
$form = \yii\widgets\ActiveForm::begin([
'id' => 'form-signup',
'action' => 'signup',
'enableAjaxValidation' => false,
'enableClientValidation' => true,
'validationUrl' => 'validation',
'validateOnBlur' => true,
'fieldConfig' => [
'template' => '<div class="col-md-4" >{label}{input}{error}</div>'
]
]);
?>
<?= $form->field($signup, 'username', ['enableAjaxValidation' => true]) ?>
<?= $form->field($signup, 'name') ?>
<?= $form->field($signup, 'family') ?>
<?= $form->field($signup, 'mobile') ?>
<?= $form->field($signup, 'password')->passwordInput() ?>
<?= $form->field($signup, 'password_repeat')->passwordInput() ?>
<?= $form->field($signup, 'email', ['enableAjaxValidation' => true]) ?>
<?= $form->field($signup, 'verifyCode', ['enableAjaxValidation' => false])->widget(yii\captcha\Captcha::className()) ?>
<div class="form-group">
<?= yii\helpers\Html::submitButton('signup', ['class' => 'btn btn-green margin-right', 'name' => 'signup-button']) ?>
</div>
controller:
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
} else {
;
\yii\widgets\ActiveForm::validate($model);
}
} else {
return $this->render('/partials/_signup', ['signup' => $model]);
}
ajax validation controller method:
public function actionValidation() {
$model = new SignupForm();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = 'json';
return \yii\widgets\ActiveForm::validate($model);
}
}
model:
public $name;
public $family;
public $mobile;
public $username;
public $email;
public $password;
public $password_repeat;
public $verifyCode;
public function rules() {
return [
[['name', 'family', 'mobile'], 'default'],
['name', 'string', 'max' => 50],
['family', 'string', 'max' => 50],
['mobile', 'string', 'max' => 11],
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'string', 'min' => 2, 'max' => 255],
[['username'], 'unique', 'targetClass' => '\frontend\models\User', 'message' => 'username already taken.'],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\frontend\models\User', 'message' => 'email name already taken.'],
['password', 'required'],
['password', 'string', 'min' => 6, 'max' => 255],
['password_repeat', 'string', 'min' => 6, 'max' => 255],
['password_repeat', 'compare', 'compareAttribute' => 'password'],
['verifyCode', 'captcha'],
];
}
there is no behaviour in controller
enableAjaxValidation of a form takes precedence over that of a field, so it's hard to tell what exactly you are trying to do with your current settings
Make sure you have verifyCode declared as an attribute on your model
Captcha verification code is saved in the session. The session key is a combination of controller's and action's ids. So you might have a misconfigured session. Or your captcha's action name is not 'captcha', - you are missing that part of your source code in the question.
Related
I am try to use unique validator for email in my model, but it doesn't work.. i mean no notification that display in form when user input the same email that already saved in db and user still can click submit button(and page reloaded) eventhough data isn't saved in db. What's wrong with my code?
this is my model validation:
['email', 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\application\common\models\User', 'message' => 'This email address has been taken.'],
this is my form :
<?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>
<?= $form->field($model,'email')->textInput()->input('email', ['placeholder' => "Email"])->label(false) ?>
...
<div class="form-group">
<?= Html::submitButton('SIGN UP NOW', ['class' => 'btn btn-sign', 'type' => 'submit']) ?>
</div>
<?php ActiveForm::end(); ?>
and this is my model to process save:
if (!$this->validate()) {
return null;
}
$user = new User();
$user->email = $this->email;
...
you should add a filter in your model validation.
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'unique',
'targetClass' => '\common\models\User',
'message' => Yii::t('frontend', 'This email address has already been taken.')
],
I'm a begginer so sorry if it's obvious. So, I would like different rules depends on what the user select. I have an update form:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'news_title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'news_content')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'check')->label('Picture update:')
->radioList(
[ 2 => 'Yes', 1 => 'No', 0 => 'Delete']) ?>
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
And only if the radioList has a value '2' I would like to require the fileInput. I mean if the user select 1 => 'No', or 0 => 'Delete' the fielInput can be empty.
public function rules() {
return [
[['news_content'], 'string'],
[['news_content'], 'required'],
[['created_at', 'updated_at'], 'safe'],
[['news_title', 'news_picture', 'created_by', 'updated_by'], 'string', 'max' => 255],
[['news_title'], 'required'],
[['news_picture'], 'required'],
[['file'], 'file', 'skipOnEmpty' => $this->checkRadio(), 'extensions' => 'png, jpg',],
[['check'], 'required', 'message' => 'Please ....'],
];
}
public function checkRadio() {
if ($this->check == 2) {
return false;
} else {
return true;
}
}
I tried to write a function in the model but the $check variable always has a 0 value and I don't really understand why. Is there any solution in Yii2 for this?
Here is the documentation which is quite straight forward but something like this should be sufficient
[
'file', 'required',
'when' => function ($model) {
return $model->check == 2;
},
'whenClient' => "function (attribute, value) {
return $('#signupform-check-2').is(':checked');
}",
'message' => 'Please....'
]
As long as you have client validation enabled, you always have to do two checks. backend and front end.
*********** Your Controller Like This ***********************
public function actionCreate(){
$model = new Model();
if(Yii::$app->request->post())
{
if($model->check ==2)
{
$model->scenario ='fileInputRequired';
}
else{
$model->scenario ='fileInputNotRequired';
}
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
********** Your Model Like This *****************
public function rules() {
return [
[['news_content','news_title','news_picture','check'], 'required'],
[['news_content'], 'string'],
[['created_at', 'updated_at'], 'safe'],
[['news_title', 'news_picture', 'created_by', 'updated_by'], 'string', 'max' => 255],
[['file'], 'file', 'on' =>'fileInputRequired', 'extensions' => 'png, jpg',],
];
}
function scenario()
{
return [
'fileInputRequired' => ['news_content', 'news_picture', 'news_title','file','check'];
'fileInputNotRequired' => ['news_content', 'news_picture','news_title','check'];
}
i have a problem. I have a required field "password". I want to ignore the last field when i clicked on "update" button. Thank you for your attention.
My rules:
public function rules()
{
return [
[['username', 'role_id', 'surname', 'name', 'patronymic', 'email', 'password', 'department_id'], 'required'],
[['role_id', 'department_id'], 'integer'],
[['date_of_birth'], 'safe'],
[['password'], 'string', 'min' => 8],
[['username', 'surname', 'name', 'patronymic', 'email', 'telephone', 'skype', 'avatar', 'password'], 'string', 'max' => 255],
[['role_id'], 'exist', 'skipOnError' => true, 'targetClass' => Roles::className(), 'targetAttribute' => ['role_id' => 'id']],
[['department_id'], 'exist', 'skipOnError' => true, 'targetClass' => Department::className(), 'targetAttribute' => ['department_id' => 'id']],
[['file'], 'file', 'extensions' => 'png, jpg'],
['email', 'email'],
[['email', 'username'], 'unique'],
];`
Also in my User models i used BeforeSave function (to hash my password, when i created a new record).
public function beforeSave($insert)
{
if (isset($this->password)) {
$this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password);
}
return parent::beforeSave($insert);
}
My controller update action:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$imageName = uniqid();
$model->file = UploadedFile::getInstance($model, 'file');
if (!empty($model->file)){
$model->file->saveAs( 'uploads/'.$imageName.'.'.$model->file->extension );
$model->avatar = 'uploads/'.$imageName.'.'.$model->file->extension;
$model->save(false);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
You can use scenarios to do this: docs, but u shouldn't hash password in beforeSave(). Like in advanced template, create setter for password OR create custom filter in rules + add scenario like 'on' => 'createUser' or 'except' => 'updateUser'.
I have my rules method like this:
public function rules()
{
return [
[['username', 'email', 'password'],'filter', 'filter' => 'trim'],
[['username', 'email', 'password'],'required', 'message' => '{attribute} can not be empty'],
['username', 'string', 'min' => 2, 'max' => 255],
['password', 'string', 'min' => 6, 'max' => 255],
['password_repeat', 'required', 'message' => 'This field can not be empty'],
['password_repeat', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match", 'skipOnError' => true],
['username', 'unique',
'targetClass' => User::className(),
'message' => 'This name is already used.'],
['email', 'email'],
['email', 'unique',
'targetClass' => User::className(),
'message' => 'This name is already used.'],
];
}
And my view code is like this:
<?php $form = ActiveForm::begin(['action' => 'login/register']); ?>
<?= $form->field($registration, 'username',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->textInput(['id' => 'register_username', 'class' => 'md-input']) ?>
<?= $form->field($registration, 'password',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->passwordInput(['id' => 'register_password', 'class' => 'md-input']) ?>
<?= $form->field($registration, 'password_repeat',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->passwordInput(['id' => 'register_password_repeat', 'class' => 'md-input']) ?>
<?= $form->field($registration, 'email',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->textInput(['id' => 'register_email', 'class' => 'md-input']) ?>
<div class="uk-margin-medium-top">
<button class="md-btn md-btn-primary md-btn-block md-btn-large">Sign in</button>
</div>
<?php ActiveForm::end(); ?>
When I'm filling all given fields I have an error Passwords don't match when repeat the password even when it's correct at first time. Is there something with my validation rules or is it a bug in Yii Validator?
UPD: I've tried 'skipOnError' => true. I found it as an answer for the similar question but it still doesn't work as it's expected.
UPD: I did some validation in my console:
var a = $('#register_password')
undefined
a.val()
"Halloha"
var b = $('#register_password_repeat')
undefined
b.val()
"Halloha"
But it still shows Passwords don't match error message
try using the rule like this
// validates if the value of "password" attribute equals to that of
['password', 'compare', 'message'=>"Passwords don't match"],
it automatically compares the password value to attribute password_repeat instead of doing it in the other order as explained in the documentation .
http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html#compare
Try avoid the id in password input (the id is automatically generated by yii2)
<?= $form->field($registration, 'password',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->passwordInput(['class' => 'md-input']) ?>
<?= $form->field($registration, 'password_repeat',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->passwordInput([ 'class' => 'md-input']) ?>
I have to create 2 signup form for different user but,I have use one table for both signup form. table is 'User' but in both form some field are different and table is same for both.But when I validate first form that time second form also validate.please help me I am new in yii2.
<?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<div class="form-group">
<button type = "submit" class = "btn btn-primary pull-right">
<strong>Signup User</strong>
</button>
</div>
<?php ActiveForm::end(); ?>
<?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>
<?= $form->field($model2, 'fname') ?>
<?= $form->field($model2, 'mname') ?>
<?= $form->field($model2, 'lname') ?>
<?= $form->field($model2, 'username') ?>
<?= $form->field($model2, 'email') ?>
<?= $form->field($model2, 'password')->passwordInput() ?>
<?= $form->field($model2, 'designation') ?>
<?= $form->field($model2, 'contact_no') ?>
<button type = "submit" class = "btn btn-success pull-right">
<strong>Signup Vendor</strong>
</button>
<?php ActiveForm::end(); ?>
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['fname', 'required'],
['mname', 'required'],
['lname', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
['password', 'required'],
['password', 'string', 'min' => 6],
['designation', 'required'],
['designation', 'string', 'max' => 100],
['contact_no', 'required'],
['contact_no', 'number', 'max' => 12],
];
}
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
return $this->redirect(['login']);
if (Yii::$app->getUser()->login($user)) {
}
}
}
$model2 = new SignupForm2();
if ($model2->load(Yii::$app->request->post())) {
if ($user = $model2->signup()) {
return $this->redirect(['login']);
if (Yii::$app->getUser()->login($user)) {
}
}
}
return $this->render('signup', [
'model' => $model,
'model2' => $model2,
]);
}
Now It's Work,I am create 2 signupForm.php in front end models.and in siteController create two models in actionSignup
validate
Change id in Active::begin
...
<?php $form = ActiveForm::begin(['id' => 'form-signup-one']); ?>
...
<?php $form = ActiveForm::begin(['id' => 'form-signup-two']); ?>
...