Yii Framework file input skipOnEmpty validation always fails - php

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() ;
}
}

Related

Saving data to db yii2

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.

Email Validation are not Working in Cakephp 3.0

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

Yii2-dynamicforms extension

I am new to yii2.0, and I'm currently creating a form po
and po_item, the problem is to update the form the modelPoItem is empty from database.
I thank those who can help me for this Home with dynamic form can be with an example. Thank you in advance
Po Controller
/**
* Updates an existing Po model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelsPoItem = [new PoItem];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
'modelsPoItem' => (empty($modelsPoItem)) ? [new PoItem] : $modelsPoItem
]);
}
}
View
<div class="po-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?= $form->field($model, 'po_no')->textInput(['maxlength' => 10]) ?>
<?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
<div class="row">
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Po Items</h4></div>
<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' => 10, // 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' => $modelsPoItem[0],
'formId' => 'dynamic-form',
'formFields' => [
'po_item_no',
'quantity',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsPoItem as $i => $modelPoItem): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Po Item</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 (! $modelPoItem->isNewRecord) {
echo Html::activeHiddenInput($modelPoItem, "[{$i}]id");
}
?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($modelPoItem, "[{$i}]po_item_no")->textInput(['maxlength' => 128]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($modelPoItem, "[{$i}]quantity")->textInput(['maxlength' => 128]) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
</div>
<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 should be change you update action like this:
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelsPoItem = $model->poItems;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$oldIDs = ArrayHelper::map($modelsPoItem, 'id', 'id');
$modelsPoItem= Model::createMultiple(PoItem::className(),$modelsPoItem);
Model::loadMultiple($modelsPoItem, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsPoItem, 'id', 'id')));
// ajax validation
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ArrayHelper::merge(
ActiveForm::validateMultiple($modelsPoItem),
ActiveForm::validate($model)
);
}
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsPoItem) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (! empty($deletedIDs)) {
PoItem::deleteAll(['id' => $deletedIDs]);
}
foreach ($modelsPoItem as $modelPoItem) {
$modelPoItem->po_id = $model->id;
if (! ( $flag = $modelPoItem->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
} else {
return $this->render('update', [
'model' => $model,
'modelsPoItem' => (empty($modelsPoItem)) ? [new Model] : $modelsPoItem
]);
}
}

Client side validation in not working

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'
],
])
;

Yii Framework - in a main view I can't add a CActiveForm because it needs a model, when I set the model nothing happens

I put this on my view, and I have to add the <?php $model = new Usuarios; ?> and it works but then actually does not send the info to the database.
I tried on another view (index view) and without this it works: <?php $model = new Usuarios; ?>.
<a class="list-group-item">
<form role="form">
<div class="form">
<?php $model = new Usuarios; ?>
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'usuarios-form',
'action' => $this->createUrl("usuarios/create"),
'enableAjaxValidation' => false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div style="padding:1px;" class="input-group input-group-sm">
<span class="input-group-addon">
<span class="glyphicon glyphicon-user" style="color:white"></span>
</span>
<?php echo $form->textField($model, 'Nombre', array('maxlength' => 128, 'placeholder' => 'Nombre y Apellido')); ?>
<?php echo $form->error($model, 'Nombre'); ?>
</div>
<div class="row buttons" style="padding:4%; color:white ; font-size:1.5vmax; font-family: Signika; border-radius:30px">
<center>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Enviar' : 'Save'); ?>
</center>
</div>
<?php $this->endWidget(); ?>
</div>
</form>
</a>
This is what your controller action should look like:
public function actionCreate() {
$model = new Usuarios;
if(isset($_POST['Usuarios'])) {
// Populate the model with values from form
// These attributes must be set to safe in the model rules() function
$model->attributes = $_POST['Usuarios'];
// ->save() will validate the model with the validation rules
// in the Usuarios.php model. If you do not want validation, use ->update()
if($model->save()) {
$this->redirect(array('view', 'id' => $model->primaryKey));
}
}
$this->render('create', array(
'model' => $model, // You pass the model to the view page
));
}
In your model, you need to update the rules() function to accept the fields for saving in the database:
public function rules() {
return array(
array('Nombre', 'safe'),
);
}

Categories