Yii2 client validation does not work - validation

I have clean yii2-advanced template installed. I created a table in DB with id and test fields. In my Model I wrote rule:
public function rules()
{
return [
[['test'], 'required'],
];
}
Also I specified an unique id for my form.
But validation does not work. After typing smth to control and focus out I have an error in console: Uncaught TypeError: Cannot read property 'required' of undefined. What can be a reason of this?
EDIT:
Model:
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
class ContactForm extends Model
{
public $name;
public function rules()
{
return [
[['name'], 'required'],
];
}
}
View:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>
<div class="site-contact">
<div class="row">
<div class="col-lg-6">
<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
<?= $form->field($model, 'name')->textInput() ?>
<?= Html::submitButton('Submit', ['class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
Controller action:
use backend\models\ContactForm;
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post())) {
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}

When you use Rules(), you must type the attribute (or array of attributes) first, and then the type of rule (that can be also a custom function by the way):
[['name'], 'required'] // setting the attribute "name" as required
you can read more about validation and rules here

if you have applied unique id for your form field, try removing it, Yii2 generates id by itself and applies validation message accordingly.

Related

Laravel problems with redirect

So I am working on a laravel project and I want that if a user types in their order code, the order will show up with the details. For some reason, the order code doesn't get through the if statement, because I get the output 'Order not found.' all the time, even if I type in an order code that is present in my orders table.
TrackController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Order;
class TrackController extends Controller
{
public function index()
{
return view ('track.index');
}
public function show($id)
{
$order = Order::where('code', $id)->first();
return view('track.show',[
'order' => $order
]);
}
public function redirect(Request $request)
{
$orderCode = $request->input('order-track-id');
$order = Order::where('code', $orderCode)->first();
if(!$order){
return redirect('/track')->with('error', 'Order not found.');
}else{
return redirect('/track/' . $order->code);
}
}
}
web.php
Route::get('/track', 'TrackController#index');
Route::post('/track/redirect', 'TrackController#redirect');
Route::get('/track/{id}', 'TrackController#show');
track.index
#extends('layouts/app')
#section('content')
<div class="container">
<div class="row justify-content center">
{!! Form::open(['action' => 'TrackController#redirect', 'method' => 'post']) !!}
{!! csrf_field() !!}
<input type="number" name="input-order-track-id" id="order-track-id">
{{ Form::button('Track', ['type' => 'submit', 'class' => 'btn btn-primary'] ) }}
{!! Form::close() !!}
</div>
</div>
#endsection
What am I doing wrong and why isn't my function putting me through to the show function in the TrackController?
In your redirect controller function.
public function redirect(Request $request)
{
$orderCode = $request->input('input-order-track-id');
$orders = Order::where('code', $orderCode)->get();
if($orders->isEmpty()){
return redirect('/track')->with('error', 'Order not found.');
}else{
$order = Order::where('code', $orderCode)->first();
return redirect('/track/' . $order->code);
}
}

Laravel simple form not setting errors and session variables

I am new to Laravel and I am trying to create a simple form that adds a record into a database table (that has 2 fields: ID and name).
Here is the code I have so far:
routes.php
Route::group(['middleware' => ['web']], function () {
Route::get('/banks/add', 'BanksController#add');
Route::post('/banks/add', 'BanksController#store');
});
BanksController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\BankFormRequest;
use App\Bank;
class BanksController extends Controller
{
public function add() {
return view('banks.add');
}
public function store(BankFormRequest $request) {
$bank = new Bank(array(
'name' => $request->get('name'),
));
$bank->save();
return redirect('/banks/add')->with('status', 'Your bank has been created! Its name is: '.$request->get('name'));
}
}
BankFormRequest.php
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class BankFormRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|unique:banks|max:255',
];
}
}
Bank.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Bank extends Model
{
public $timestamps = false;
protected $guarded = ['id'];
}
banks/add.php
<form id="registerForm" role="form" method="post">
<pre><?=var_dump($errors)?></pre>
<pre>
<?php if (session()->has('status')): ?>
<?=session('status')?>
<?php endif; ?>
</pre>
<?php if (isset($errors) && $errors->any()): ?>
<?php foreach ($errors->all() as $error): ?>
<p class="alert alert-danger"><?=$erorr?></p>
<?php endforeach; ?>
<?php endif; ?>
<input type="hidden" name="_token" value="<?=csrf_token()?>">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" placeholder="Bank name" name="name">
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
banks table
CREATE TABLE `banks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
In the banks/add view I have the form and 2 var_dumps of the $errors and session('status') variables, but they are always NULL. Otherwise, the form validator works well and it inserts my input into the database if it passes the rules I defined.
Anyone knows what causes my errors to not be shown?
in your banks/add.php
<p class="alert alert-danger"><?=$erorr?></p>
$erorr is wrong
If you are using laravel 5.2 try to remove web middleware on the route group this will fix your problem. why? because the RouteServiceProvider class will add it for you.
line 53 - 60 as of this writing.
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}

Yii2 rule array validation

I have 2 models A and B where A has many B.
Now i want to create multiple B at the same time(page).
Here is my codes.
B.php
...
public function rules()
{
return [
[['username', 'xx', 'yy'], 'required'],
[['xx', 'yy'], 'string'],
[['username'], 'string', 'max' => 255]
];
}
...
_form.php
<div class="b-form">
<?php $form = ActiveForm::begin(); ?>
<?php for ($i=0; $i < 3; $i++) {
?>
<h3>B #<?=$i+1?></h3>
<hr />
<?= $form->field($model, 'xx[]')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'yy[]')->textInput(['maxlength' => true]) ?>
<?php
}
?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
I want to make those 6(3x2) text inputs responds individually and at least need 2 pairs of xx and yy to pass validation.
Now how do i build good rules to cover my needs?
There is dedicated section about it in official docs - Collecting Tabular Input.
Example of controller:
<?php
namespace app\controllers;
use Yii;
use yii\base\Model;
use yii\web\Controller;
use app\models\Setting;
class SettingsController extends Controller
{
// ...
public function actionUpdate()
{
$settings = Setting::find()->indexBy('id')->all();
if (Model::loadMultiple($settings, Yii::$app->request->post()) && Model::validateMultiple($settings)) {
foreach ($settings as $setting) {
$setting->save(false);
}
return $this->redirect('index');
}
return $this->render('update', ['settings' => $settings]);
}
}
Used methods:
Model::loadMultiple() - load post data into an array of models.
Model::validateMultiple() - validates an array of models.
There is more info, for example how to create a dynamic set of new records, use it if you need it.
Also, take a look to some extensions for easing work with multiple inputs, for example unclead/yii2-multiple-input or wbraganca/yii2-dynamicform.
I want to make those 6(3x2) text inputs responds individually and at
least need 2 pairs of xx and yy to pass validation.
This sounds weird, you should never trust and always validate ALL data coming from user.

Yii2 - ActiveForm ajax submit

How can i use ActiveForm with these requirements?
Submit form with ajax.
Before submitting with ajax: Check if error exits.
After submitting: Display error of field under field's input if the server responses unsuccess saving result.
This is your form in view. I prefer use different actions for validation and saving. You can join them into single method.
<?php $form = \yii\widgets\ActiveForm::begin([
'id' => 'my-form-id',
'action' => 'save-url',
'enableAjaxValidation' => true,
'validationUrl' => 'validation-rul',
]); ?>
<?= $form->field($model, 'email')->textInput(); ?>
<?= Html::submitButton('Submit'); ?>
<?php $form->end(); ?>
In validation action you should write. It validates your form and returns list of errrs to client. :
public function actionValidate()
{
$model = new MyModel();
$request = \Yii::$app->getRequest();
if ($request->isPost && $model->load($request->post())) {
\Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
And this is save action. In validate input data for security:
public function actionSave()
{
$model = new MyModel();
$request = \Yii::$app->getRequest();
if ($request->isPost && $model->load($request->post())) {
\Yii::$app->response->format = Response::FORMAT_JSON;
return ['success' => $model->save()];
}
return $this->renderAjax('registration', [
'model' => $model,
]);
}
This code will validate your form in actionValidate() and. For submitting your form via AJAX use beforeSubmit event. In your javascript file write:
$(document).on("beforeSubmit", "#my-form-id", function () {
// send data to actionSave by ajax request.
return false; // Cancel form submitting.
});
That's all.
Submit form with ajax.
Before submitting with ajax: Check if error exits. yii display error if any by default....... :)
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $model backend\models\search\JobSearch */
/* #var $form yii\bootstrap\ActiveForm */
?>
<div class="job-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
//'method' => 'get',
'options' => ['id' => 'dynamic-form111']
]); ?>
<?php echo $form->field($searchModel, 'id') ?>
<?php echo $form->field($searchModel, 'user_id') ?>
<?php echo $form->field($searchModel, 'com_id') ?>
<?php echo $form->field($searchModel, 'job_no') ?>
<?php echo $form->field($searchModel, 'court_id') ?>
<?php // echo $form->field($model, 'case_no') ?>
<?php // echo $form->field($model, 'plainttiff') ?>
<?php // echo $form->field($model, 'defendant') ?>
<?php // echo $form->field($model, 'date_fill') ?>
<?php // echo $form->field($model, 'court_date') ?>
<?php // echo $form->field($model, 'status_id') ?>
<?php // echo $form->field($model, 'created_at') ?>
<?php // echo $form->field($model, 'updated_at') ?>
<div class="form-group">
<?php echo Html::submitButton('Search', ['class' => 'btn btn-primary','id'=>'submit_id']) ?>
<?php echo Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('body').on('beforeSubmit', 'form#dynamic-form111', function () {
var form = $(this);
// return false if form still have some validation errors
if (form.find('.has-error').length)
{
return false;
}
// submit form
$.ajax({
url : form.attr('action'),
type : 'get',
data : form.serialize(),
success: function (response)
{
var getupdatedata = $(response).find('#filter_id_test');
// $.pjax.reload('#note_update_id'); for pjax update
$('#yiiikap').html(getupdatedata);
//console.log(getupdatedata);
},
error : function ()
{
console.log('internal server error');
}
});
return false;
});
});
</script>

Codeigniter: Not inserting data in table

Update: It is solved ..
For some reason, the data is not getting inserted into the table. It is however being posted from the form as I could see with var dump, but further than that, won't do. So, here are the 3 modules. It is a very simple test scheme: Just a form with two fields, you press Submit and should be inserted. (I can do all that in ordinary PHP with one page, but, the MVC frameworks are a nightmare in this regard, you write about 30 times more code than you would need in procedural.
<?php
class Inserting_controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Inserting_model');
}
public function index ()
{
$this->load->view('inserting_view');
}
// Controller
public function insert()
{
$data = array(
'username' => $this->input->post('username', TRUE),
'password' => sha1($this->input->post('password', TRUE)
));
var_dump($data); // We do get the data posted
exit;
$this->Inserting_model->insertdata($data); // this should forward them to the Model
}
}
?>
==============
MODEL
<?php
class Inserting_model extends CI_Model{
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->database();
}
public function insertdata($data)
{
$this->db->insert('users', $data);
}
}
?>
========
VIEW
<div id="inserting_form">
<?php echo form_open('index.php/Inserting_controller/insert/'); ?>
<ul>
<li>
<label>Username</label>
<div><?php echo form_input(array('id' => 'username', 'name' => 'username')); ?></div>
</li>
<li>
<label>Password</label>
<div><?php echo form_password(array('id' => 'password', 'name' => 'password')); ?></div>
</li>
<li><?php echo validation_errors();?></li>
<li><?php echo form_submit(array('name' =>'submit'),'Insert');?> </li>
</ul>
<?php echo form_close(); ?>
</div>
Blushing :/
On writing the debugging code, I forgot to delete the exit; thus, the program exited right after that ....

Resources