Email validation is not working and if i take name of the field as email only then it take is email but also not perfect validation like 'a#a' is working if i take it as email otherwise only non-empty is working only.
RecommendTable.php
<?php
namespace App\Model\Table;
use App\Model\Entity\recommend;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\Validation\Validator;
class RecommendTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->table('recommend');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
}
public function validationDefault(Validator $validator)
{
$validator = new Validator();
$validator
->requirePresence('name')
->notEmpty('name', 'Please fill this field')
->add('name', [
'length' => [
'rule' => ['minLength', 10],
'message' => 'Titles need to be at least 10 characters long',
]
]);
$validator->add("emai", "validFormat", [
"rule" => ["email"],
"message" => "Email must be valid."
]);
$validator
->requirePresence('yemail')
->notEmpty('yemail', 'Please fill this field..')
->add('yemail', ['length' => ['rule' => ['minLength', 10],'message' => 'Titles need to be at least 10 characters long',]]);
return $validator;
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['email']));
return $rules;
}
}
Recommend.php
<?php
namespace App\Model\Entity;
use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\Entity;
class Recommend extends Entity
{
protected $_accessible = [
'*' => true,
'id' => false,
];
protected function _setPassword($value)
{
$hasher = new DefaultPasswordHasher();
return $hasher->hash($value);
}
}
Index.ctp
<?= $this->Form->create($temp) ?>
<div class="row">
<div class="container">
<div class="comment-form">
<div class="row">
<div>
<h2>
<center>
Recommend us to your Friends/Library
</center>
</h2>
</div><fieldset>
<div class="col-md-12 col-sm-12">
<div class="input-container">
<?php
echo $this->Form->input('emai',array('id'=>'emai','label'=>'To ( Receiver’s mail-ID)',"placeholder"=>"Send E-mail to multiple (seperated by commas).")) ?>
</div>
</div>
<div class="col-md-6 col-sm-3">
<div class="input-container">
<?php
echo $this->Form->input('name',array('id'=>'name','label'=>'Name',"placeholder"=>"Name")); ?>
</div>
</div>
<div class="col-md-6 col-sm-3">
<div class="input-container">
<?php
echo $this->Form->input('yemail',array('id'=>'yemail','label'=>'From',"placeholder"=>"From")); ?>
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="input-container">
<label>Message</label>
<textarea name="msg" id="msg" style="resize: none;text-align:justify; " disabled placeholder="Hello"></textarea>
</div>
</div>
</fieldset>
<div class="col-md-12 col-sm-12">
<div class="input-container">
<?= $this->Form->button(__('Submit')) ?>
<button type="Reset">Reset</button>
<?= $this->Form->end() ?></div>
Recommend Controller
<?php
namespace App\Controller;
use Cake\ORM\TableRegistry;
use App\Controller\AppController;
use Cake\Mailer\Email;
use Cake\ORM\Table;
use App\Model\Tabel\RecommendTabel;
use Cake\Event\Event;
class RecommendController extends AppController
{
public function index()
{
$temp = $this->Recommend->newEntity();
if ($this->request->is('post')) {
$temp = $this->Recommend->patchEntity($temp, $this->request->data);
if($temp) {
$name=$this->request->data('name');
$receiver_email=$this->request->data('emai');
$Subject_Title='Temp';
$Sender_email=$this->request->data('yemail');
$email = new Email();
$email->template('invite', 'default')
->viewVars(['value' => $name])
->emailFormat('html')
->from($Sender_email)
->to($receiver_email)
->subject($Subject_Title)
->send();
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'add']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('temp'));
$this->set('_serialize', ['temp']);
}
The patchEntity function returns a patched entity. So, the result of this line will always evaluate to true when used in a boolean context.
$temp = $this->Recommend->patchEntity($temp, $this->request->data);
So, to check whether any errors were detected, your if statement cannot just compare the returned value to true, but instead do something like this:
if (!$temp->errors()) {
Cakephp is provide in defult validation library, please find this validation in (i.e. http://book.cakephp.org/2.0/en/models/data-validation.html). Please try to use this code.
public $validate = array('email' => array('rule' => 'email'));
public $validate = array(
'email' => array(
'rule' => array('email', true),
'message' => 'Please supply a valid email address.'
)
);
Related
I am using live wire and when I try to validate the form it say
Method Livewire\Redirector::withInput does not exist.
and this is my code
Posts.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Post;
class Posts extends Component
{
public $title;
public $content;
public function hydrate(){
$this->validate([
'title' => 'required',
'content' => 'required'
]);
}
public function save(){
$data = [
'title' => $this->title,
'content' => $this->content,
'user_id' => Auth()->user()->id
];
Post::create($data);
$this->cleanVars();
}
private function cleanVars(){
$this->title = null;
$this->content = null;
}
public function render()
{
return view('livewire.posts');
}
}
livewire view
<div>
<label>Title</label>
<input wire:model="title" type="text" class="form-control" />
#error('title')
<p class="text-danger">{{ $message }}</p>
#enderror
<label>Content</label>
<textarea wire:model="content" type="text" class="form-control"></textarea>
#error('content')
<p class="text-danger">{{ $message }}</p>
#enderror
<br />
<button wire:click="save" class="btn btn-primary">Save</button>
</div>
also I putted this view in home.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Dashboard') }}</div>
<div class="card-body">
#livewire('posts')
</div>
</div>
</div>
</div>
</div>
#endsection
Really you need to fix the header of this question, is repeating the same and you're missing something there to the community. I see in your code this and I dislike this use
public function hydrate(){
$this->validate([
'title' => 'required',
'content' => 'required'
]);
}
I mean, this validation running on every hydration isn't a good approach of this. Instead, declare the rules
protected $rules = [// rules here];
//or
public function rules()
{
return [
//rules here
];
}
then you can validate the entries, for example on real-time validation using the validateOnly method inside the updated()
public function updated($propertyName)
{
$this->validateOnly($propertyName, $this->rules());
}
or just use it in the save method
public function save()
{
$this->validate(); // in the protected $rules property
// or
Post::create($this->validate());
}
I banged my head against the walls for 2 days now and I can't seem to shake this error.
I am receiving this error:
ErrorException (E_WARNING)
array_map(): Argument #2 should be an array
What I am trying to do: Each user can have a list of urls in the database. The same url can be in two or more user account, so it is a many to many relationship.
My UrlsController looks like this:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Urls;
use Illuminate\Http\Request;
use Auth;
class UrlsController extends Controller
{
public function __construct() {
$this->middleware('auth');
}
public function index(User $user)
{
return view('editurl', compact('user'));
}
public function store(User $user) {
$user_id = Auth::user()->id;
$data = request()->validate([
'user_id' => $user_id,
'url' => 'required',
]);
auth()->user()->userurls()->create([
'user_id' => $data['user_id'],
'url' => $data['url'],
]);
return redirect("/url/" . auth()->user()->id);
}
}
My Urls model looks like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Urls extends Model
{
//protected $quarded = [];
protected $fillable = ['user_id','url'];
protected $table = 'userUrls';
public function user()
{
return $this->belongsToMany(User::class);
}
}
My blade file looks like this:
#extends('layouts.pagprincipala')
#section('content')
<section id="home" class="home pt-5 pb-5">
<div class="container mb-5">
<div class="row">
<div class="col-md-8">
<h1 class="h4">Adaugare url-uri</h1>
<hr class="bg-dark w-25 ml-0">
<p>
<form action="/url/{{$user->id}}" enctype="multipart/form-data" method="post">
#csrf
<div class="row">
<div class="col-8 offset-2">
<div class="form-group row">
<label for="url" class="col-md-12 col-form-label">Adaugare URL (doar emag si pcgarage)</label>
<input id="url"
type="text"
class="form-control{{$errors->has('url') ? 'is-invalid' : ''}}"
name="url"
autocomplete="url" autofocus>
#if($errors->has('url'))
<span class="invalid-feedback" role="alert">
<strong class="text-danger">Campul url este obligatoriu.</strong>
</span>
#endif
</div>
<div class="row pt-4">
<button class="btn btn-primary">Adaugare URL</button>
</div>
</div>
</div>
</form>
</p>
</div>
</div>
</div>
</section>
#endsection
Also, my routes look like this:
Route::get('/url/{user}', 'UrlsController#index')->name('editurl');
Route::post('/url/{user}', 'UrlsController#store')->name('updateurl');
Can you give me a suggestion on how to move forward from this ?!
The problem is in your validator:
$data = request()->validate([
'user_id' => $user_id,
'url' => 'required',
]);
You try to validate the user_id with a rule that is the user id. What you probably want to achieve is 'user_id' => 'integer', or you can drop this rule all together as you know who the user is because of Auth()->user(). This should do:
$data = request()->validate([
'url' => 'required|url', //checks if it is an URL
]);
What we don't know is how your User model is constructed. With a many to many you need a pivot table urls_users or user_urls_users with url_id and user_id which means you don't need a user_id in the userUrls table, just id and url. But that's another issue. If you want to make sure any user has any url only once, you can use the ->sync() methode.
I'm trying to save data from my form to db. But when I click "submit" button nothing happened(page is refresh but my db table is blank) what I did wrong?
I'm create model which extend ActiveRecord:
class EntryForm extends \yii\db\ActiveRecord
{
public $id;
public $name;
public $email;
public $age;
public $height;
public $weight;
public $city;
public $checkboxList;
public $checkboxList1;
public $imageFiles;
public function rules()
{
return [
[['name', 'email','age','height','weight','city','checkboxList','checkboxList1'], 'required'],
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg','maxFiles' => 5],
['email', 'email'],
];
}
public static function tableName()
{
return 'form';
}
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'name',
'email' => 'e-mail',
'age' => 'age',
'height' => 'height',
'weight' => 'weight',
'city' => 'city',
'checkboxList' => 'technies',
'checkboxList1' => 'english_level',
'imageFiles[0]' => 'photo_1',
'imageFiles[1]' => 'photo_2',
'imageFiles[2]' => 'photo_3',
'imageFiles[3]' => 'photo_4',
'imageFiles[4]' => 'photo_5'
];
}
public function insertFormData()
{
$entryForm = new EntryForm();
$entryForm->name = $this->name;
$entryForm->email = $this->email;
$entryForm->age = $this->age;
$entryForm->height = $this->height;
$entryForm->weight = $this->weight;
$entryForm->city = $this->city;
$entryForm->checkboxList = $this->checkboxList;
$entryForm->checkboxList1 = $this->checkboxList1;
$entryForm->imageFiles = $this->imageFiles;
return $form->save();
}
public function contact($email)
{
if ($this->validate()) {
Yii::$app->mailer->compose()
->setTo($email)
->setFrom('prozrostl#gmail.com')
->setSubject('Email from test app')
->setTextBody($this->name + $this->age + $this->height + $this->width + $this->city + $this->checkboxList + $this->checkboxList1 + $this->imageFiles)
->send();
return true;
} else {
return false;
}
}
}
then I update my view file to show the form, view it's just easy few fields and upload files button(but all information doesn't save)
<?php $form = ActiveForm::begin([
'id' => 'my-form',
'options' => ['enctype' => 'multipart/form-data']
]); ?>
<div class="row">
<div class="col-lg-6">
<?= $form->field($entryForm, 'name')->textInput(['class'=>'name_class'])->input('name',['placeholder' => "Имя"])->label(false); ?>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'email')->textInput()->input('email',['placeholder' => "E-mail"])->label(false); ?>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<?= $form->field($entryForm, 'age')->textInput()->input('age',['placeholder' => "Возраст(полных лет)"])->label(false); ?>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'height')->textInput()->input('height',['placeholder' => "Рост"])->label(false); ?>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<?= $form->field($entryForm, 'weight')->textInput()->input('weight',['placeholder' => "Вес"])->label(false); ?>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'city')->textInput()->input('city',['placeholder' => "Город проживания"])->label(false); ?>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<p><img class="describe_images" src="computer.png"></img>Нужна ли техника в аренду</p>
</div>
<?= $form->field($entryForm, 'checkboxList')->checkboxList(['no'=>'Нет', 'yes_camera'=>'Да,только камера', 'yes_both'=>'да,компьютер и камера'])->label(false) ?>
</div>
<div class="row">
<div class="col-lg-3">
<p><img class="describe_images" src="English.png"></img>Знание английского</p>
</div>
<?= $form->field($entryForm, 'checkboxList1')->checkboxList(['starter'=>'Без знания', 'elementary'=>'Базовый', 'intermediate'=>'Средний','up-intermediate'=>'Высокий','advanced'=>'Превосходный'])->label(false) ?>
</div>
<div class="row">
<div class="col-lg-6">
<div class="col-lg-6">
<p class="add_photo"><img class="describe_images" src="photo.png"></img>Добавить фото(до 5 штук)</p>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*','id'=>'gallery-photo-add'])->label(false) ?>
</div>
</div>
<div class="col-lg-6 pixels-line">
<div class="preview"></div>
</div>
</div>
<div class="form-group">
<?= Html::submitButton('Отправить', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end() ?>
and then I add that code to my controller. I created new action ActionForm and put into that code:
public function actionForm()
{
$entryForm = new EntryForm();
if ($entryForm->load(Yii::$app->request->post()) && $entryForm->insertFormData()) {
}
}
Why do you redeclare the variables in the database? you're basically telling yii to ignore the attributes on the table.
public $id;
public $name;
public $email;
public $age;
public $height;
public $weight;
public $city;
public $checkboxList;
public $checkboxList1;
public $imageFiles;
Remove the public declarations and see if it works.
Your code looks ok, so probably you have some validation errors.
In the insertFormData() method add the following to get the validation errors:
if (!$entryForm->validate()){
var_dump($entryForm->getErrors());
}
Later edit:
Your insertFormData method is basically useless because the $entryForm->load loads the data from POST.
The second problem is probably with the file upload. To get the uploaded files use UploadedFile::getInstance($model, 'imageFile'). More info here
I suggest you to create a crud using Gii (the crud generator) and then implement the file upload according to the documentation mentioned above. And in this case you will see the validation errors too.
I am currently doing a project in PHP Yii framework.
I have a form with file input field called company_logo.For the field I have added the following rule in the model [['company_logo'],'file','skipOnEmpty'=>false]
When I upload file, it shows
Please upload a file.
even if I uploaded a file.
When I remove the
skipOnEmpty
it is uploading the file.I have researched several places for the issue.But couldn't find a solution.
The controller, view and model are given below
View - add_company.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/*Assigning the parameters to be accessible by layouts*/
foreach($layout_params as $layout_param => $value) {
$this->params[$layout_param] = $value;
}
?>
<div class="form-group">
</div>
<div class="col-md-12">
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Add Company</h3>
</div><!-- /.box-header -->
<!-- form start -->
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<div class="box-body">
<?php if(isset($message)&&sizeof($message)): ?>
<div class="form-group">
<div class="callout callout-info alert-dismissible">
<h4><?php if(isset($message['title']))echo $message['title'];?></h4>
<p>
<?php if(isset($message['body']))echo $message['body'];?>
</p>
</div>
</div>
<?php endif;?>
<div class="form-group">
<?= $form->field($model, 'company_name')->textInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'company_address')->textArea(array('class'=>'form-control')); ?>
</textarea>
<div class="form-group">
<?= $form->field($model, 'company_logo')->fileInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_name')->textInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_email')->textInput(array('class'=>'form-control','type'=>'email')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_phone_number')->textInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_password')->passwordInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'retype_admin_password')->passwordInput(array('class'=>'form-control')); ?>
</div>
<div class="box-footer">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
</div><!-- /.box-body -->
<?php ActiveForm::end(); ?>
</div>
</div>
Controller - CompanyController.php
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\CompanyModel;
use yii\web\UploadedFile;
global $username;
class CompanyController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionEntry()
{
}
public function actionAdd() {
$layout_params=array(
'username'=>'admin',
'sidebar_menu1_class' =>'active',
'sidebar_menu12_class' =>'active',
'dash_title' => 'Companies',
'dash_sub_title'=>'Add new company'
);
$message = array();
$model = new CompanyModel();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
echo "hello";
$model->company_logo = UploadedFile::getInstance($model, 'company_logo');
echo "world";
if ($model->company_logo && $model->validate()) {
$model->company_logo->saveAs('uploads/' . $model->company_logo->baseName . '.' . $model->company_logo->extension);
} else {
echo "Yo Yio ture";
exit;
}
$model->add_company();
$message['title'] = 'Wow !';
$message['body'] = 'Successfully added company '.$model->company_name;
}else {
$message = $model->getErrors();
// print_r( $message );
// exit;
}
return $this->render('add-company', ['model' => $model,
'layout_params'=>$layout_params,
'message' =>$message
]);
//return $this->render('add-company',$data);
}
public function actionSave() {
//print_r($_POST);
}
public function actionIndex()
{
$data = array(
'layout_params'=>array(
'username'=>'admin',
'sidebar_menu11_class' =>'active'
)
);//
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
}
Model - CompanyModel.php
<?php
namespace app\models;
use yii;
use yii\db;
use yii\base\Model;
use yii\web\UploadedFile;
class CompanyModel extends Model
{
public $company_name;
public $company_address;
public $company_logo;
public $admin_email;
public $admin_name;
public $admin_password;
public $retype_admin_password;
public $admin_phone_number;
public function rules()
{
return [
[['company_name'], 'required'],
[['company_address'],'required'],
[['admin_name'],'required'],
[['admin_email'],'required'],
[['admin_password'],'required'],
[['retype_admin_password'],'required'],
[['admin_phone_number'],'required'],
[['company_logo'],'file','skipOnEmpty'=>false]
];
}
public function add_company() {
Yii::$app->db->close();
Yii::$app->db->open();
$comm = Yii::$app->db->createCommand("CALL create_company('".$this->company_name."','".$this->company_address."','".$this->admin_email."','".$this->admin_phone_number."',1)");
return $comm->execute() ;
}
}
<?php
namespace app\models;
use yii;
use yii\db;
use yii\base\Model;
use yii\web\UploadedFile;
class CompanyModel extends Model
{
public $company_name;
public $company_address;
public $company_logo;
public $admin_email;
public $admin_name;
public $admin_password;
public $retype_admin_password;
public $admin_phone_number;
public function rules()
{
return [
[['company_name'], 'required'],
[['company_address'],'required'],
[['admin_name'],'required'],
[['admin_email'],'required'],
[['admin_password'],'required'],
[['retype_admin_password'],'required'],
[['admin_phone_number'],'required'],
[['company_logo'],'file','skipOnEmpty'=>false],//here the comma is missing
];
}
public function add_company() {
Yii::$app->db->close();
Yii::$app->db->open();
$comm = Yii::$app->db->createCommand("CALL create_company('".$this->company_name."','".$this->company_address."','".$this->admin_email."','".$this->admin_phone_number."',1)");
return $comm->execute() ;
}
}
I am working client side validation in yii2 but it is not working for me.
View File
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\captcha\Captcha;
?>
<ul class="breadcrumb">
<li>Home</li>
<li>Pages</li>
<li class="active">Login</li>
</ul>
<!-- BEGIN SIDEBAR & CONTENT -->
<div class="row margin-bottom-40">
<!-- BEGIN SIDEBAR -->
<!--<div class="sidebar col-md-3 col-sm-3">
<ul class="list-group margin-bottom-25 sidebar-menu">
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Register</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Restore Password</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> My account</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Address book</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Wish list</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Returns</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Newsletter</li>
</ul>
</div>-->
<!-- END SIDEBAR -->
<!-- BEGIN CONTENT -->
<div class="col-md-9 col-sm-9">
<h1>Login</h1>
<div class="content-form-page">
<div class="row">
<div class="col-md-7 col-sm-7">
<?php $form = ActiveForm::begin(['id' => 'login-form','class' => 'form-horizontal form-without-legend']); ?>
<?php echo $form->errorSummary($model); ?>
<div class="form-group">
<label for="email" class="col-lg-4 control-label">Email <span class="require">*</span></label>
<div class="col-lg-8">
<?= $form->field($model, 'username',['template' => "{input}"])->textInput(array('placeholder' => 'Username','class'=>'form-control validate[required]')); ?>
</div>
</div>
<div class="form-group">
<label for="password" class="col-lg-4 control-label">Password <span class="require">*</span></label>
<div class="col-lg-8">
<?= $form->field($model, 'password',['template' => "{input}"])->passwordInput(array('class'=>'form-control validate[required]','placeholder'=>'Password')); ?>
<!--<input type="text" class="form-control" id="password">-->
</div>
</div>
<div class="row">
<div class="col-lg-8 col-md-offset-4 padding-left-0">
Forget Password?
</div>
</div>
<div class="row">
<div class="col-lg-8 col-md-offset-4 padding-left-0 padding-top-20">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
<!--<button type="submit" class="btn btn-primary">Login</button>-->
</div>
</div>
<div class="row">
<div class="col-lg-8 col-md-offset-4 padding-left-0 padding-top-10 padding-right-30">
<hr>
<div class="login-socio">
<p class="text-muted">or login using:</p>
<ul class="social-icons">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
</div>
<?php ActiveForm::end(); ?>
<!--</form>-->
</div>
<!--<div class="col-md-4 col-sm-4 pull-right">
<div class="form-info">
<h2><em>Important</em> Information</h2>
<p>Duis autem vel eum iriure at dolor vulputate velit esse vel molestie at dolore.</p>
<button type="button" class="btn btn-default">More details</button>
</div>
</div>-->
</div>
</div>
</div>
<!-- END CONTENT -->
</div>
<!-- END SIDEBAR & CONTENT -->
Colntroller File
<?php
namespace frontend\controllers;
use frontend\models\Users;
use backend\models\SmsData;
use backend\models\SmsDataSearch;
use Yii;
use frontend\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\ArrayDataProvider;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login','index', 'error','register'],
'allow' => true,
],
[
'actions' => ['logout','report','create','delete'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
// 'logout' => ['post'],
],
],
];
}
/**
* #inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionIndex()
{
return $this->render('index');
}
public function actionRegister()
{
$model = new Users();
if($model->load(Yii::$app->request->post()))
{
$model->status='0';
$model->is_delete='0';
$model->created_by='1';
$model->password=md5($_POST['Users']['password']);
$model->created_date=date('Y-m-d h:i:s');
$model->role_type='1';
$model->save();
Yii::$app->session->setFlash('success', 'You Have Successfully Register');
return $this->redirect(array('login'));
}
return $this->render('register',['model'=>$model]);
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
$data=Yii::$app->db->createCommand("select * from `users` where user_id = '".Yii::$app->user->getId()."'")->queryAll();
if($data[0]['role_type'] == '1')
{
Yii::$app->session->setFlash('success', 'You Have Successfully LogIn');
return $this->redirect(array('report'));
}
elseif($data[0]['role_type'] =='0')
{
Yii::$app->session->setFlash('success', 'You Have Successfully LogIn');
$url=Yii::$app->urlManager->createUrl('users/index');
return $this->redirect($url);
}
} else {
return $this->render('login',[
'model' => $model,
]);
}
}
public function actionReport()
{
$model= new SmsData();
if($model->load(Yii::$app->request->post()))
{
$fromdate=date('Y-m-d',strtotime($_POST['SmsData']['fromDate']));
$todate = date('Y-m-d',strtotime($_POST['SmsData']['toDate']));
$query="SELECT s.*,r.description as ratingtext FROM sms_data s
INNER JOIN users u ON u.unique_id = s.client_id
LEFT JOIN rating r ON r.rating = s.rating
WHERE u.user_id = '".Yii::$app->user->getId()."' AND s.message_id != '9999' AND date(s.created_date) >= '".$fromdate."' AND date(s.created_date) <= '".$todate."'";
$data=Yii::$app->db->createCommand($query)->queryAll();
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
$model->fromDate=$_POST['SmsData']['fromDate'];
$model->toDate=$_POST['SmsData']['toDate'];
return $this->render('report',['dataProvider'=>$provider,'model'=>$model]);
}
else
{
$query="SELECT s.*,r.description as ratingtext FROM sms_data s
INNER JOIN users u ON u.unique_id = s.client_id
LEFT JOIN rating r ON r.rating = s.rating
WHERE u.user_id = '".Yii::$app->user->getId()."' AND s.message_id != '9999' ";
$data=Yii::$app->db->createCommand($query)->queryAll();
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('report',['dataProvider'=>$provider,'model'=>$model]);
}
}
public function actionCreate()
{
$model = new SmsData();
if($model->load(Yii::$app->request->post())) {
$clientID=\frontend\models\Users::findOne(Yii::$app->user->getId());
$model->created_by = Yii::$app->user->getId();
$model->created_date= date('Y-m-d',strtotime($_POST['SmsData']['created_date']));
$model->rating = $_POST['SmsData']['rating'];
$model->text = $_POST['SmsData']['text'];
$model->message_id = 9999;
$model->client_id = $clientID->unique_id;
$model->save();
Yii::$app->session->setFlash('success', 'Data Inserted Successfully');
return $this->redirect(array('create'));
} else {
$query="SELECT s.*,r.description as ratingtext FROM sms_data s
INNER JOIN users u ON u.unique_id = s.client_id
LEFT JOIN rating r ON r.rating = s.rating
WHERE u.user_id = '".Yii::$app->user->getId()."' AND message_id = 9999
AND s.is_delete = 0 AND s.status = 1";
$data=Yii::$app->db->createCommand($query)->queryAll();
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('create',['model'=>$model,'dataProvider'=>$provider]);
}
}
public function actionDelete($id) {
$model = new SmsData();
$command = Yii::$app->db->createCommand('UPDATE sms_data SET is_delete = 1 WHERE sms_id='.$id);
$command->execute();
Yii::$app->session->setFlash('success', 'Deleted Successfully ');
return $this->redirect(array('create'));
}
public function actionLogout()
{
Yii::$app->user->logout();
Yii::$app->session->setFlash('success', 'You Have Successfully Logout');
return $this->goHome();
}
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending email.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
public function actionAbout()
{
return $this->render('about');
}
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
public function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->getSession()->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->getSession()->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
}
}
return $this->render('requestPasswordResetToken', [
'model' => $model,
]);
}
public function actionResetPassword($token)
{
try {
$model = new ResetPasswordForm($token);
} catch (InvalidParamException $e) {
throw new BadRequestHttpException($e->getMessage());
}
if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
Yii::$app->getSession()->setFlash('success', 'New password was saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
}
}
Model :
<?php
namespace frontend\models;
use frontend\models\Users;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
private $_id = false;
private $_name;
/**
* #inheritdoc
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*/
public function validatePassword()
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError('password', 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
*
* #return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
/**
* Finds user by [[username]]
*
* #return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = Users::findByUsername($this->username);
}
return $this->_user;
}
public function getId()
{
if ($this->_id === false) {
$this->_id = $this->user_id;
}
return $this->_id;
}
}
What i need to do for client side validation ? Server side validation is working for me.
This is not a bug! You have to use ActiveForm::validate() for send errors back the browser as it formats the attributes same as ActiveForm renders
if (Yii::$app->request->isAjax && $model->load($_POST))
{
Yii::$app->response->format = 'json';
return \yii\widgets\ActiveForm::validate($model);
}
To enable AJAX validation for the whole form, you have to set the
yii\widgets\ActiveForm::enableAjaxValidation
property to be true and specify id to be a unique form identifier:
$form = ActiveForm::begin([
'id' => 'register-form',
'enableClientValidation' => true,
'options' => [
'validateOnSubmit' => true,
'class' => 'form'
],
])
;