YII2 Validation for several forms in one action - php

Hellow i'm making several forms and their validation on YII with ajax and i have some problems
Here the view code:
<?
$form = ActiveForm::begin([
'id' => 'test-form',
'options' => ['class' => 'form-horizontal'],
]) ?>
<?= $form->field($model, 'name')->textInput(['placeholder' => "Имя"])->label('Имя'); ?>
<?= $form->field($model, 'lastname')->textInput(['placeholder' => "Фамилия"])->label('Фамилия'); ?>
<?= $form->field($model, 'country')->textInput(['placeholder' => "Страна"])->label('Страна'); ?>
<?= $form->field($model, 'pindex')->textInput(['placeholder' => "Индекс"])->label('Индекс'); ?>
<?= $form->field($model, 'card') ->textInput(['placeholder' => "Ваш номер карты xxxx xxxx xxxx xxxx"])->label('Номер карты');?>
<?= $form->field($model, 'form_name')->hiddenInput(['value' => 'Form']) ?>
<div class="form-group">
<div class="">
<?= Html::submitButton('Отправить', ['class' => 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end() ?>
<?
$form = ActiveForm::begin([
'id' => 'mobile-form',
'options' => ['class' => 'form-horizontal'],
]) ?>
<?= $form->field($model2, 'name')->textInput(['placeholder' => "Имя"])->label('Имя'); ?>
<?= $form->field($model2, 'lastname')->textInput(['placeholder' => "Фамилия"])->label('Фамилия'); ?>
<?= $form->field($model2, 'country')->textInput(['placeholder' => "Страна"])->label('Страна'); ?>
<?= $form->field($model2, 'pindex')->textInput(['placeholder' => "Индекс"])->label('Индекс'); ?>
<?= $form->field($model2, 'phone') ->textInput(['placeholder' => "Ваш телефон"])->label('Ваш телефон');?>
<?= $form->field($model2, 'form_name')->hiddenInput(['value' => 'Mobile']) ?>
<div class="form-group">
<div class="">
<?= Html::submitButton('Отправить', ['class' => 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end() ?>
Then im sending data with ajax to controller, code:
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\MainForm;
use app\models\EntryForm;
use app\models\EntryMobile;
class SiteController extends Controller
{
/**
* {#inheritdoc}
*/
public function actionEntry(){
$model = new EntryForm;
$model2 = new EntryMobile;
if(Yii::$app->request->isAjax) {
$model->load(Yii::$app->request->post());
$model2->load(Yii::$app->request->post());
if($model->validate() || $model2->validate()){
$json['ok'] = "";
}else{
$json['error'] = " ";
}
Yii::$app->response->format = Response::FORMAT_JSON;
return $json;
} else {
return $this->render('entry', ['model' => $model,'model2' => $model2]);
}
}
In models i have MainForm , and EntryForm and EntryMobile that extends MainForm with their own rules.
Here is a question:
How to make $model->validation() and $model2->validation() in one method? Or how to make the controller method width on model for two forms. Scenarios doesnt work cause they made me make the same. Two object and etc. Please help

You can use bitwise and for testing both models validations. Like:
$model->validate() & $model2->validate()
Which will then proceed only if both conditions are true but will test both of them anyway (which should throw the validation errors you expect to see).

Related

How to create a dynamic list of the same form on Yii2?

How do I create a dynamic list of the same form and show it on the view on Yii2 (it can be viewed as a list of the same object with different information) Thanks.
I have the following form on /frontend/views/site/example.php
That form I want to put it on a list.
<div class="site-example">
<h1><?= Html::encode($this->title) ?></h1>
<p>Example of a list:</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'form-example']); ?>
<?= $form->field($model, 'email')->textInput(['readonly' => true, 'value' => $email]) ?>
<?= $form->field($model, 'lastname')->textInput(['readonly' => true, 'value' => $lastname]) ?>
<?= $form->field($model, 'phone')->textInput(['readonly' => true, 'value' => $phone]) ?>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
Assuming this is your controller.
<?php
namespace frontend\controllers;
use Yii;
use yii\base\Model;
use yii\web\Controller;
use frontend\models\YourForm;
class SiteController extends Controller
{
public function actionYourAction()
{
$forms = [new YourForm, new YourForm, new YourForm];
return $this->render('example', [
'forms' => $forms
]);
}
}
Then your view could be below
<div class="site-example">
<h1><?= Html::encode($this->title) ?></h1>
<p>Example of a list:</p>
<div class="row">
<div class="col-lg-5">
<?php foreach ($forms as $index => $form): ?>
<?php $form = ActiveForm::begin(['options' => ['id' => "form-example-$index"]]); ?>
<?= $form->field($form, "[$index]email")->textInput(['readonly' => true, 'value' => $form->email]) ?>
<?= $form->field($form, "[$index]lastname")->textInput(['readonly' => true, 'value' => $form->lastname]) ?>
<?= $form->field($form, "[$index]phone")->textInput(['readonly' => true, 'value' => $form->phone]) ?>
<?php ActiveForm::end(); ?>
<?php endforeach; ?>
</div>
</div>
</div>

When value in dropdownlist have ever been selected will not display

I have two tables that relate to each other one to one that is Husband and Wife. I've made my value dropdownlist and to get the data from the table Husband. I want when its value had been chosen will not appear on his dropdownlist. Perhaps there are other references or can be helped. For the code can be seen in the image below.
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\models\Husband;
/* #var $this yii\web\View */
/* #var $model app\models\Wife */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="wife-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'id_husband')->dropDownList(
ArrayHelper::map(Husband::find()->where('status' => 0)->all(), 'id_husband', 'name'),
['prompt' => 'Pilih']
) ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'status')->dropDownList(['0' => 'Tidak Aktif', '1' => 'Aktif'],
['prompt'=>'--Pilih--', 'style' => 'width:380px']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
You forgot to mention as array in the where condition .
Use ->where(['status' => 0])" instead of "->where('status' => 0)
So it is:
<?= $form->field($model, 'id_husband')->dropDownList(
ArrayHelper::map(Husband::find()->where(['status' => 0])->all(), 'id_husband', 'name'),
['prompt' => 'Pilih']
) ?>

How to use 2 form tag in same page in Yii

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.

Yii2 model with scenarios save all except the password field

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';

Yii2 : Dynamic Form wbraganca

I want to use dynamic form widget (wbraganca). I tried it using the tutorial by 'doingItEasy' channel & also by github. And wrote following code :
controller code -
public function actionCreate()
{
$model = new Vendors();
$modelsSubCat = [new BusinessSubCategories];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$modelsSubCat = Model::createMultiple(BusinessSubCategories::classname());
Model::loadMultiple($modelsSubCat, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsSubCat) && $valid;
$modelsSubCat = Model::createMultiple(BusinessSubCategories::classname());
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsSubCat as $modelSubCat) {
$model->ven_sub_category_id = $modelSubCat->bsc_id;
if (! ($flag = $modelSubCat->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->ven_id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
} else {
return $this->render('create', [
'model' => $model,
'modelsSubCat' => (empty($modelsSubCat)) ? [new BusinessSubCategories] : $modelsSubCat
]);
}
}
'_form.php' code -
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
?>
<div class="vendors-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?= $form->field($model, 'ven_company_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_main_category_id')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_sub_category_id')->textInput() ?>
<div class="row">
<div class="panel panel-default">
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 4, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsSubCat[0],
'formId' => 'dynamic-form',
'formFields' => [
// 'bsc_id',
'bsc_name',
'bsc_image',
'bsc_description',
'bmc_id',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsSubCat as $i => $modelSubCat): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Sub Categories</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelSubCat->isNewRecord) {
echo Html::activeHiddenInput($modelSubCat, "[{$i}]id");
}
?>
<?= $form->field($modelSubCat, "[{$i}]bsc_name")->textInput(['maxlength' => true]) ?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($modelSubCat, "[{$i}]bsc_image")->fileInput(); ?>
</div>
<div class="col-sm-6">
<?= $form->field($modelSubCat, "[{$i}]bsc_description")->textInput(['maxlength' => true]) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
<?= $form->field($model, 'ven_services_offered')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_business_logo')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_company_descr')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_established_date')->textInput() ?>
<?= $form->field($model, 'ven_noof_emp')->textInput() ?>
<?= $form->field($model, 'ven_branches_loc')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_market_area')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_website')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_specialized_in')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_contact_no')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_email_id')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_address')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_country_id')->textInput() ?>
<?= $form->field($model, 'ven_state_id')->textInput() ?>
<?= $form->field($model, 'ven_city_id')->textInput() ?>
<?= $form->field($model, 'ven_location_id')->textInput() ?>
<?= $form->field($model, 'ven_zip')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ven_contact_person_id')->textInput() ?>
<?= $form->field($model, 'ven_verified')->dropDownList([ 'Y' => 'Y', 'N' => 'N', ], ['prompt' => '']) ?>
<?= $form->field($model, 'ven_created')->textInput() ?>
<?= $form->field($model, 'ven_updated')->textInput() ?>
<?= $form->field($model, 'ven_deleted')->dropDownList([ 'Y' => 'Y', 'N' => 'N', ], ['prompt' => '']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<script type="text/javascript">
$(".dynamicform_wrapper").on("beforeInsert", function(e, item) {
console.log("beforeInsert");
});
$(".dynamicform_wrapper").on("afterInsert", function(e, item) {
console.log("afterInsert");
});
$(".dynamicform_wrapper").on("beforeDelete", function(e, item) {
if (! confirm("Are you sure you want to delete this item?")) {
return false;
}
return true;
});
$(".dynamicform_wrapper").on("afterDelete", function(e) {
console.log("Deleted item!");
});
$(".dynamicform_wrapper").on("limitReached", function(e, item) {
alert("Limit reached");
});
</script>
'create.php' code -
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model backend\models\Vendors */
$this->title = Yii::t('app', 'Create Vendors');
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Vendors'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="vendors-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
'modelsSubCat' => $modelsSubCat
]) ?>
</div>
But What happens is that the add/remove button is not working. I'm showing it's screenshot - Screenshot with Add/remove buttons
1)first add
$form = ActiveForm::begin([
'options' => [
'enctype' => 'multipart/form-data',
'id' => 'dynamic-form'
]
]);
instead your
2) delete 'bmc_id' from attributes of dynamic form or add textinput to dynamic form with bmc_id column
3) check if exist your model Model (...Model::loadMultiple($modelsSubCat, Yii::$app->request->post());)
I tried, but i can't reproduce this issue here. Can you try fix the following lines and see if the problem was there?
You are not closing the <div class="row"> after the dynamic form.
This could mess up the html code.
In your formFields, you don't need to add the 'bmc_id' if the
model have one. Remove it. By the way, you are using:
Html::activeHiddenInput($modelSubCat, "[{$i}]id");
Make sure this is the correct name of the attribute.
Non-related with your issue, you have a second:
$modelsSubCat = Model::createMultiple(BusinessSubCategories::classname());
After the loadMultiple method, making it useless.
EDIT
Just occurred to me: by any chance you have more than one DynamicForm in the same view? Or the code is the same as you posted?

Categories