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']); ?>
...
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'];
}
Hello I am working on Yii2 project. I have user module, in that while update any user the input filed password is coming with original password. I want to make password field null on update page.
I am using password hash, but in update page password coming with its original value, I tried to null that filed but with bad luck.
I tried :
<?= $form->field($model, 'password_hash')->passwordInput(['maxlength' => true,'value'=>null]) ?>
Even I tried
$model->password_hash="" in controller but nothing happen.
But nothing happen still password field coming with its value.
This is my user model rules :
public function rules() {
return [
[['first_name', 'last_name', 'address', 'mobile', 'email', 'password_hash', 'role_id'], 'required'],
[['address'], 'string'],
[['role_id'], 'integer'],
[['email'], 'email'],
[['email'], 'unique', 'targetAttribute' => ['email']],
[['created_at', 'updated_at'], 'safe'],
[['first_name', 'last_name', 'email', 'password_hash'], 'string', 'max' => 255],
[['mobile'], 'required','on'=>'create,update'],
//[['mobile'], 'string','max'=>10],
[['mobile'], 'number','numberPattern' => '/^[0-9]{10}$/','message'=>"Mobile must be integer and should not greater then 10 digit"],
[['password_hash'],'string','min'=>6],
//[['mobile'], 'number'],
[['status'], 'string', 'max' => 1,'on'=>'create,update'],
[['role_id'], 'exist', 'skipOnError' => true, 'targetClass' => Roles::className(), 'targetAttribute' => ['role_id' => 'id']],
];
}
User controller :
public function actionUpdate($id)
{
$model = $this->findModel($id);
$roles= Roles::find()->all();
$model->password_hash="";
if ($model->load(Yii::$app->request->post())) {
$input=Yii::$app->request->post();
if($input['Users']['password_hash']!=""){
$model->password_hash=User::setPassword($model->password_hash);
}
//$model->auth_key=User::generateAuthKey();
$model->status=$input['Users']['status'];
unset($model->created_at);
$model->updated_at=date('Y-m-d H:i:s');
//echo "<pre>";print_r($model);exit;
$model->save();
Yii::$app->session->setFlash('success', "Record has been updated successfully !");
//return $this->redirect(['view', 'id' => $model->id]);
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $model,
'roles'=>$roles
]);
}
}
User Form :
<?php $form = ActiveForm::begin(); ?>
<div class="row">
<div class="col-md-4">
<?= $form->field($model, 'first_name')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'last_name')->textInput(['maxlength' => true]) ?>
</div>
</div>
<div class="row">
<div class="col-md-8">
<?= $form->field($model, 'address')->textarea(['rows' => 6]) ?>
</div>
</div>
<div class="row">
<div class="col-md-4">
<?= $form->field($model, 'mobile')->textInput(['maxlength' => true]) ?>
</div>
</div>
<div class="row">
<div class="col-md-4">
<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'password_hash')->passwordInput(['maxlength' => true,'value'=>""]) ?>
</div>
</div>
<div class="row">
<div class="col-md-4">
<?= $form->field($model, 'status')->dropDownList(['0'=>'Active','1'=>'InActive']); ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'role_id')->dropDownList(ArrayHelper::map(Roles::find()->all(),'id','name')) ?>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => 'btn green']) ?>
<?= Html::a('Cancel', ['/ag-consumer'], ['class' => 'btn default']) ?>
</div>
<?php ActiveForm::end(); ?>
Dont take password_hash. You have to create new variable in model e.g password
public $password;
public function rules() {
return [
[['first_name', 'last_name', 'address', 'mobile', 'email', 'password', 'role_id'], 'required'],
[['address'], 'string'],
[['role_id'], 'integer'],
[['email'], 'email'],
[['email'], 'unique', 'targetAttribute' => ['email']],
[['created_at', 'updated_at'], 'safe'],
[['first_name', 'last_name', 'email', 'password'], 'string', 'max' => 255],
[['mobile'], 'required','on'=>'create,update'],
//[['mobile'], 'string','max'=>10],
[['mobile'], 'number','numberPattern' => '/^[0-9]{10}$/','message'=>"Mobile must be integer and should not greater then 10 digit"],
[['password'],'string','min'=>6],
//[['mobile'], 'number'],
[['status'], 'string', 'max' => 1,'on'=>'create,update'],
[['role_id'], 'exist', 'skipOnError' => true, 'targetClass' => Roles::className(), 'targetAttribute' => ['role_id' => 'id']],
];
}
View
<?= $form->field($model, 'password')->passwordInput(['maxlength' => true,'value'=>null]) ?>
Model or Controler example
if ($this->validate()) {
$user = User::findOne($id);
$user->setPassword($this->password);
$user->generateAuthKey();
$user->save(false);
}
Why not remove it on update at all?
Like so :
<?= $model->isNewRecord ? $form->field($model, 'password_hash')->passwordInput(['maxlength' => true]) : "" ?>
Happy coding. :)
UPDATE
If the password field is really need to be there, then try this in Controller :
public function actionUpdate($id)
{
$model = $this->findModel($id);
$password = $model->password_hash; // backup the value first;
$model->password_hash = "";
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->password_hash = $password; // retreive the value back
$model->save();
// redirect here
}
return $this->render('update', [
'model' => $model,
]);
}
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.
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']) ?>