CakePHP 3 : default validation not working - validation

I am working in CakePHP 3.2. I have users table and register action in UsersController.
I'm trying to add a new record but default validation is not working.
This is my 'UsersTable.php`
<?php
namespace App\Model\Table;
use App\Model\Entity\User;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Auth\DefaultPasswordHasher;
use Cake\Validation\Validator;
class UsersTable extends Table
{
/**
* Initialize method
*
* #param array $config The configuration for the Table.
* #return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->displayField('name');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('UserAddresses', [
'foreignKey' => 'user_id'
]);
}
/**
* Default validation rules.
*
* #param \Cake\Validation\Validator $validator Validator instance.
* #return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->uuid('id')
->allowEmpty('id', 'create');
$validator
->notEmpty('name');
$validator
->email('email')
->notEmpty('email');
$validator
->add('mobile', [
'minLength' => [
'rule' => ['minLength', 10],
'message' => 'Mobile number must be of 10 characters long',
],
'maxLength' => [
'rule' => ['maxLength', 10],
'message' => 'Mobile number must be of 10 characters long',
]
])
->numeric('mobile')
->notEmpty('mobile');
$validator
->notEmpty('password');
$validator
->add('newPassword', [
'compare' => [
'rule' => ['compareWith', 'confirmNewPassword'],
]
])
->notEmpty('newPassword');
$validator
->add('confirmNewPassword', [
'compare' => [
'rule' => ['compareWith', 'newPassword'],
'message' => 'Password does not match'
]
])
->notEmpty('confirmNewPassword');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* #param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* #return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['email']));
return $rules;
}
public function validationPassword(Validator $validator)
{
$validator
->add('old_password', 'custom', [
'rule' => function($value, $context){
$user = $this->get($context['data']['id']);
if ($user) {
if((new DefaultPasswordHasher)->check($value, $user->password)) {
return true;
}
}
return false;
},
'message' => 'The old password does not match the current password!',
])
->notEmpty('old_password');
$validator
->add('password1', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'The Password have to be at least 6 characters!',
]
])
->add('password1', [
'match' => [
'rule' => ['compareWith', 'password2'],
'message' => 'The passwords does not match!',
]
])
->notEmpty('password1');
$validator
->add('password2', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'The Password have to be at least 6 characters!',
]
])
->add('password2', [
'match' => [
'rule' => ['compareWith', 'password1'],
'message' => 'The passwords does not match!',
]
])
->notEmpty('password2');
return $validator;
}
}
register() method
public function register()
{
// if already logged in, redirect to referer action to prevent new registration
if (!empty($this->Auth->user('id'))) {
return $this->redirect($this->referer());
}
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
// check user exists or not
$userExists = $this->Users->find('all', [
'conditions' => [
'OR' => [
'email' => $this->request->data['email'],
'mobile' => $this->request->data['mobile'],
]
]
]);
if ($userExists->count() > 0) {
$userExists = $userExists->first();
$this->Flash->success(__('It seems you are already registered. Please login using your email or mobile and passowrd'));
return $this->redirect(['controller' => 'Users', 'action' => 'login']);
}
$hash = hash('sha256',date('YmdHis').time());
$user->tmp_hash = $hash;
$user->verified = 0;
$user = $this->Users->patchEntity($user, $this->request->data);
if ($u = $this->Users->save($user)) {
// send verification email
if ($this->sendEmail($user->id, $user->email, $hash, 'register')) {
$this->Flash->registerSuccess(__('Thank you. You need to verify email. Not received verification email ?'), [
'params' => [
'userId' => $user->id
],
['escape' => false]
]);
return $this->redirect(['action' => 'login']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
return $this->redirect(['action' => 'login']);
}
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
register.ctp view
<?= $this->Form->create(null, ['url' => ['controller' => 'Users', 'action' => 'register'], 'class' => 'regForm']) ?>
<div class="form-group">
<label>Name <?= $this->Form->error('name') ?></label>
<?= $this->Form->input('name', ['class' => 'form-control', 'label' => false, 'placeholder' => 'Enter Your Name', 'title' => 'Please Enter your full name']) ?>
</div>
<div class="form-group">
<label>Email address</label>
<?= $this->Form->input('email', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Enter Email', 'title' => 'Please enter valid email']) ?>
</div>
<div class="form-group">
<label>Mobile</label>
<?= $this->Form->input('mobile', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Mobile Number', 'title' => 'Please enter valid mobile no to receive notifications']) ?>
</div>
<div class="form-group">
<label>Password</label>
<?= $this->Form->input('password', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Password', 'title' => 'Please enter password']) ?>
</div>
<?= $this->Form->button('<i class="fa fa-user"></i> Create and account', ['type' => 'submit', 'class' => 'btn btn-primary', 'escape' => false]) ?>
<?= $this->Form->end() ?>
</div>
When I try to submit form without filling anything, it simply refreshes the form without showing validation error.

In your register.ctp file
$this->Form->create(null, ['url' => ['controller' => 'Users', 'action' => 'register'], 'class' => 'regForm']);
Replace it with
$this->Form->create($user, ['url' => ['controller' => 'Users', 'action' => 'register'], 'class' => 'regForm']);
As per concept of CakePHP v3 you have to pass entity in Form Creation method so it will display form validation error in view.

Related

Notice: Undefined index

I have this error message when I submit form.
Notice: Undefined index: title in
C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php
on line 38
Notice: Undefined index: description in
C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php
on line 39
Notice: Undefined index: featured in
C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php
on line 58
Message:
An exception occurred while executing 'INSERT INTO auto (title,
description, featured, date_created) VALUES (?, ?, ?, ?)' with params
[null, null, null, "2017-06-15 05:04:44"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title'
cannot be null
this is my form and fieldset
use Zend\Form\Fieldset;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use BusinessGhana\Entity\Autos;
class AddFieldset extends Fieldset
{
protected $objectManager;
public function init()
{
$this->add([
'type' => 'text',
'name' => 'title',
'attributes' => [
'id' => 'autoTitle'
],
'options' => [
'label' => 'Title',
'display_empty_item' => true,
'empty_item_label' => 'Maximum of 60 characters',
],
]);
$this->add([
'type' => 'textarea',
'name' => 'description',
'attributes' => [
'id' => 'autoDescription'
],
'options' => [
'label' => 'Description',
'display_empty_item' => true,
'empty_item_label' => 'description',
],
]);
$this->add([
'type' => 'radio',
'name' => 'featured',
'attributes' => [
'id' => 'autoFeatured'
],
'options' => array(
'label' => 'Featured',
'value_options' => array(
array('value' => '0',
'label' => 'No',
'selected' => true,
'label_attributes' => array(
'class' => 'col-sm-2 btn btn-default',
),
),
array(
'value' => '1',
'label' => 'Yes',
'label_attributes' => array(
'class' => 'col-sm-2 btn btn-danger',
),
),
),
'column-size' => 'sm-12',
'label_attributes' => array(
'class' => 'col-sm-2',
),
),
]);
}
}
use Zend\Form\Form;
//use Zend\InputFilter\InputFilter;
class AddForm extends Form
{
public function init()
{
$this->add([
'name' => 'dependentForm',
'type' => AddFieldset::class,
]);
$this->add([
'type' => 'submit',
'name' => 'submit',
'attributes' => [
'value' => 'Submit',
],
]);
}
}
This is my controller action
public function addAction()
{
// Create the form.
$form = new PostForm();
if ($this->getRequest()->isPost()) {
// Get POST data.
$data = $this->params()->fromPost();
// Fill form with data.
$form->setData($data);
if ($form->isValid()) {
// Get validated form data.
$data = $form->getData();
$this->AutosManager->addNewAutos($data);
return $this->redirect()->toRoute('retrieve');
}
}
return new ViewModel([
'form' => $form
]);
}
I know hydration can solve this problem but I don't know how to use it yet.
thanks for any help.
this is my autosManager
class AutosManager
{
/**
* Entity manager.
* #var Doctrine\ORM\EntityManager;
*/
private $entityManager;
/**
* Constructor.
*/
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
public function addNewAutos($data)
{
$autos = new Autos();
$autos->setTitle($data['title']);
$autos->setDescription($data['description']);
$autos->setFeatured($data['featured']);
$currentDate = date('Y-m-d H:i:s');
$autos->setDateCreated($currentDate);
$this->entityManager->persist($autos);
$this->entityManager->flush();
}
}
i can retrieve data from database.
This is where i render my forms:
$form = $this->form;
$fieldset = $form->get('dependentForm');
$title = $fieldset->get('title');
$title->setAttribute('class', 'form-control');
$title->setAttribute('placeholder', 'Maximum of 60 characters');
$title->setAttribute('id', 'autoTitle');
$description = $fieldset->get('description');
$description->setAttribute('class', 'form-control');
$description->setAttribute('placeholder', 'Description here...');
$description->setAttribute('id', 'autoDescription');
$featured = $fieldset->get('featured');
$featured->setAttribute('id', 'autoRadio');
$form->get('submit')->setAttributes(['class'=>'btn btn-primary']);
$form->prepare();
echo $this->form()->openTag($form);
?>
<fieldset>
<div class="form-group">
<?= $this->formLabel($title) ?>
<?= $this->formElement($title) ?>
<?= $this->formElementErrors()->render($title,['class'=>'help-block'])?>
</div>
<div class="form-group">
<?= $this->formLabel($description) ?>
<?= $this->formElement($description) ?>
<?=$this->formElementErrors()->render($description,
['class'=>'help-block'])?>
</div>
<div class="form-group">
<?= $this->formLabel($featured) ?>
<?= $this->formElement($featured) ?>
<?= $this->formElementErrors()->render($featured,
['class' =>'help-block']) ?>
</div>
</div></div><div class="row">
<div class="col-md-4">
</fieldset>
<?= $this->formElement($form->get('submit')); ?>
In your function addNewAutos($data) : your $data variable don't have title, description and featured fields. So php consider these as null, and your $this->entityManager->flush() will try to write null values in database, but you have a constraint that at least title must not be null.
So check your $data array contains the title, description and featured fields before to initiate your Auto object...

yii2: new action is notFound 404

i want add a new action in my controller in yii2 project :
i have error for add any new action !
new action have this error : Not Found (#404)
<?php
namespace soft\controllers;
use Yii;
use soft\models\Reserve;
use soft\models\ReserveSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use \yii\web\Response;
use yii\helpers\Html;
/**
* ReserveController implements the CRUD actions for Reserve model.
*/
class ReserveController extends Controller {
/**
* #inheritdoc
*/
public function behaviors() {
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
'bulk-delete' => ['post'],
],
],
];
}
/**
* Lists all Reserve models.
* #return mixed
*/
public function actionIndex() {
$searchModel = new ReserveSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
public function actionJson() {
die;
}
/**
* Displays a single Reserve model.
* #param string $id
* #return mixed
*/
public function actionView($id) {
$request = Yii::$app->request;
if ($request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return [
'title' => "Reserve #" . $id,
'content' => $this->renderAjax('view', [
'model' => $this->findModel($id),
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::a('Edit', ['update', 'id' => $id], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
];
} else {
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
}
/**
* Creates a new Reserve model.
* For ajax request will return json object
* and for non-ajax request if creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate() {
$request = Yii::$app->request;
$model = new Reserve();
if ($request->isAjax) {
/*
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
if ($request->isGet) {
return [
'title' => "Create new Reserve",
'content' => $this->renderAjax('create', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
} else if ($model->load($request->post()) && $model->save()) {
return [
'forceReload' => '#crud-datatable-pjax',
'title' => "Create new Reserve",
'content' => '<span class="text-success">Create Reserve success</span>',
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::a('Create More', ['create'], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
];
} else {
return [
'title' => "Create new Reserve",
'content' => $this->renderAjax('create', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
} else {
/*
* Process for non-ajax request
*/
if ($model->load($request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
}
/**
* Updates an existing Reserve model.
* For ajax request will return json object
* and for non-ajax request if update is successful, the browser will be redirected to the 'view' page.
* #param string $id
* #return mixed
*/
public function actionUpdate($id) {
$request = Yii::$app->request;
$model = $this->findModel($id);
if ($request->isAjax) {
/*
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
if ($request->isGet) {
return [
'title' => "Update Reserve #" . $id,
'content' => $this->renderAjax('update', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
} else if ($model->load($request->post()) && $model->save()) {
return [
'forceReload' => '#crud-datatable-pjax',
'title' => "Reserve #" . $id,
'content' => $this->renderAjax('view', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::a('Edit', ['update', 'id' => $id], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
];
} else {
return [
'title' => "Update Reserve #" . $id,
'content' => $this->renderAjax('update', [
'model' => $model,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
} else {
/*
* Process for non-ajax request
*/
if ($model->load($request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
}
/**
* Delete an existing Reserve model.
* For ajax request will return json object
* and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
* #param string $id
* #return mixed
*/
public function actionDelete($id) {
$request = Yii::$app->request;
$this->findModel($id)->delete();
if ($request->isAjax) {
/*
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
return ['forceClose' => true, 'forceReload' => '#crud-datatable-pjax'];
} else {
/*
* Process for non-ajax request
*/
return $this->redirect(['index']);
}
}
/**
* Delete multiple existing Reserve model.
* For ajax request will return json object
* and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
* #param string $id
* #return mixed
*/
public function actionBulkDelete() {
$request = Yii::$app->request;
$pks = explode(',', $request->post('pks')); // Array or selected records primary keys
foreach ($pks as $pk) {
$model = $this->findModel($pk);
$model->delete();
}
if ($request->isAjax) {
/*
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
return ['forceClose' => true, 'forceReload' => '#crud-datatable-pjax'];
} else {
/*
* Process for non-ajax request
*/
return $this->redirect(['index']);
}
}
/**
* Finds the Reserve model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param string $id
* #return Reserve the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id) {
if (($model = Reserve::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
why action json is
not found but action create is Available ؟!
this is working :admin2.localhost/en/reserve/create
but this is not working : admin2.localhost/en/reserve/json
this is my main.php :
<?php
$params = array_merge(
require (__DIR__ . '/../../common/config/params.php'),
require (__DIR__ . '/params.php')
);
$config = [
'id' => 'app-soft',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'soft\controllers',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'user' => [
'identityClass' => 'main\models\custom\SoftUser',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'aaaaaaaaaaaaaaa',
],
'runtime'=>[
'class'=>'soft\config\Runtime',
],
'urlManager' => [
'rules' => [
'package' => 'site/package',
],
],
],
'params' => $params,
];
return $config;
Thank you for your guidance.
my params.php have problem and fixed :
'urlRules' => [
'' => 'site/index',
'login/' => 'site/login',
'signup/' => 'site/signup',
'<controller:[\w-]+>/<action:\w+>' => '<controller>/<action>',
'<controller:[\w-]+>/<id:\d+>' => '<controller>/view',
'<controller:[\w-]+>/create' => '<controller>/create',
'<controller:[\w-]+>/update/<id:\d+>' => '<controller>/update',
'<controller:[\w-]+>/delete/<id:\d+>' => '<controller>/delete',
'<controller:[\w-]+>/bulk-delete' => '<controller>/bulk-delete',
]

CakePHP 3 : Retrieving data from database using Ajax

I am working on a CakePHP 3 project which is having a Apply Coupon form.
I want to apply the coupon using Ajax.
The view of coupon form is
<?= $this->Form->create(null, [
'url' => ['controller' => 'Coupons', 'action' => 'checkCoupon'],
'name' => 'checkCoupon'
]) ?>
<?= $this->Form->input('coupon_code', [
'type' => 'text',
'placeholder' => 'Apply Coupon Code',
'label' => false
]) ?>
<?= $this->Form->submit('Apply Coupon') ?>
and the checkCoupon action in CouponsController is
public function checkCoupon()
{
$this->request->onlyAllow('ajax'); // No direct access via browser URL
if ($this->request->is('post')) {
$couponCode = $this->request->data['coupon_code'];
$couponCheck = $this->Coupons->find('all', [
'conditions' => [
'coupon_code' => $couponCode
]
]);
if ($couponCheck->count() === 1) {
$coupon = $couponCheck->first();
$valid_till = $coupon->valid_till;
$dt = new Time($valid_till);
$date = $dt->format('Y-m-d');
if ($date >= date('Y-m-d')) {
echo 'Coupon is Valid. Discount of '.$coupon->value.'has been applied';
} else {
echo 'Coupon is Expired';
}
} else {
echo 'This is not a valid coupon code';
}
}
}
I want the $coupon->value and $coupon->id to be retrieved and added to the checkout link as
<?= $this->Html->link(__('Confirm Checkout'), ['controller' => 'ServiceRequests', 'action' => 'confirmCheckout', $service->id, $primaryAddressId, $serviceArea->id, $coupon->id], ['class' => 'btn btn-block btn-success']) ?>
The Apply Coupon form is in checkout action of RequestsController
Also the form is working well. I have checked it by removing the onlyAllow('ajax') line and printing values in check_coupon.ctp view.
How could I do it using Ajax ?
Edit 2 : checkout.ctp
<div class="form-info coupon">
<?= $this->Form->create(null, [
'url' => ['controller' => 'Coupons', 'action' => 'ajax_checkCoupon'],
'name' => 'checkCoupon',
'id' => 'checkCoupon'
]) ?>
<?= $this->Form->input('coupon_code', [
'type' => 'text',
'placeholder' => 'Apply Coupon Code',
'label' => false
]) ?>
<label class="hvr-sweep-to-right">
<?= $this->Form->submit('Apply Coupon', ['id' => 'applyCoupon']) ?>
</label>
<label id="couponUpdate"></label>
<label id="loading" style="display:none;">Loading...</label>
<?php
$data = $this->Html->script('#checkCoupon')->serializeForm(['isForm' => true, 'inline' => true]);
$this->Html->script('#checkCoupon')->event(
'submit',
$this->Html->script(
[
'controller' => 'Coupons',
'action' => 'ajax_checkCoupon'
],
[
'update' => '#couponUpdate',
'data' => $data,
'async' => true,
'dataExpression' => true,
'before' => "$('#loading').fadeIn();$('#applyCoupon').attr('disabled','disabled');",
'complete' => "$('#loading').fadeOut();$('#applyCoupon').removeAttr('disabled');"
]
)
);
?>
</div>
Error : Call to a member function serializeForm() on string on line 18 in checkout.ctp

Unable to set validation rules loaded from config file codeigniter

My config file
config/login_rules
i have defined my login form validation rules here
<?php
/**
* SETTING VALIDATION RULES FOR THE LOGIN FORM
*/
$config['login_settings'] = array(
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required|trim|min_length[6]|max_length[20]|xss_clean',
'errors' => array(
'required' => 'You must provide a %s.',
),
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|trim|valid_email|xss_clean'
)
);
/**
* SETTING ATTRIBUTES FOR THE LOGIN FORM
*/
$config['login_attribute'] = array(
'form' => array(
'id' => 'loginform',
'class' => 'form-horizontal',
'role' => 'form'
),
'email'=> array(
'id'=>'login-username',
'class' => 'form-control',
'name'=>'email',
'placeholder' => 'Enter Email',
'value'=>set_value('email')
),
'password' =>array(
'id'=>'login-password',
'class' => 'form-control',
'name'=>'password',
'placeholder'=>'Enter Password'
),
'checkbox' =>array(
'id' => 'login-remember',
'class' => 'form-control',
'name' => 'remember_me',
'value' => '1',
'checked' => TRUE
),
'submit' =>array(
'id' => 'btn-login',
'class' => 'btn btn-success',
'name' => 'submit',
'value' => 'Login'
)
);
?>
My Controller (Login.php)
in my controller i am loading the config file trying to apply validation rules for it
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class login extends CI_Controller {
public function __construct()
{
parent::__construct();
//$this->output->enable_profiler(TRUE);
}
public function index()
{
echo 'login controller index fun';
}
public function login()
{
$this->config->load('login_rules');
$this->form_validation->set_rules($this->config->item('login_settings'));
$data["login_attrib"] = $this->config->item("login_attribute");
if ($this->form_validation->run() == FALSE)
{
$this->load->view('login_form',$data["login_attrib"]);
}
else
{
echo 'Success';
}
}
}
?>
i am not getting any error , nor the validation rules are working
View file (login_form.php)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<html>
<head>
<title>Admin Login</title>
</head>
<body>
<?php echo validation_errors();
echo form_open('login/login',$form);
echo form_input($email);
echo form_input($password);
echo form_submit($submit);
echo form_close();
?>
</body>
</html>
Try this .
$this->config->load('login_rules');
$this->form_validation->set_rules($this->config->item('login_settings'));
It will be useful for you.

Validation Errors not showing

I am trying to validate a user when they register to my application. Nothing is getting set to validationErrors, which is strange can anyone help me out?
Here is my MembersController
<?php
class MembersController extends AppController {
var $name = 'Members';
var $components = array('RequestHandler','Uploader.Uploader');
function beforeFilter() {
parent::beforeFilter();
$this->layout = 'area';
$this->Auth->allow('register');
$this->Auth->loginRedirect = array('controller' => 'members', 'action' => 'dashboard');
$this->Uploader->uploadDir = 'files/avatars/';
$this->Uploader->maxFileSize = '2M';
}
function login() {}
function logout() {
$this->redirect($this->Auth->logout());
}
function register() {
if ($this->data) {
if ($this->data['Member']['psword'] == $this->Auth->password($this->data['Member']['psword_confirm'])) {
$this->Member->create();
if ($this->Member->save($this->data)) {
$this->Auth->login($this->data);
$this->redirect(array('action' => 'dashboard'));
} else {
$this->Session->setFlash(__('Account could not be created', true));
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
}
}
}
}
}
?>
Member Model
<?php
class Member extends AppModel {
var $name = 'Member';
var $actsAs = array('Searchable');
var $validate = array(
'first_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter your first name'
),
'last_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => "Please enter your last name"
),
'email_address' => array(
'loginRule-1' => array(
'rule' => 'email',
'message' => 'please enter a valid email address',
'last' => true
),
'loginRule-2' => array(
'rule' => 'isUnique',
'message' => 'It looks like that email has been used before'
)
),
'psword' => array(
'rule' => array('minLength',8),
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a password with a minimum lenght of 8 characters.'
)
);
var $hasOne = array('Avatar');
var $hasMany = array(
'Favourite' => array(
'className' => 'Favourite',
'foreignKey' => 'member_id',
'dependent' => false
),
'Friend' => array(
'className' => 'Friend',
'foreignKey' => 'member_id',
'dependent' => false
),
'Guestbook' => array(
'className' => 'Guestbook',
'foreignKey' => 'member_id',
'dependent' => false
),
'Accommodation'
);
var $hasAndBelongsToMany = array('Interest' => array(
'fields' => array('id','interest')
)
);
function beforeSave($options = array()) {
parent::beforeSave();
if (isset($this->data[$this->alias]['interests']) && !empty($this->data[$this->alias]['interests'])) {
$tagIds = $this->Interest->saveMemberInterests($this->data[$this->alias]['interests']);
unset($this->data[$this->alias]['interests']);
$this->data[$this->Interest->alias][$this->Interest->alias] = $tagIds;
}
$this->data['Member']['first_name'] = Inflector::humanize($this->data['Member']['first_name']);
$this->data['Member']['last_name'] = Inflector::humanize($this->data['Member']['last_name']);
return true;
}
}
?>
login.ctp
<div id="login-form" class="round">
<h2>Sign In</h2>
<?php echo $form->create('Member', array('action' => 'login')); ?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->end('Sign In');?>
</div>
<div id="signup-form" class="round">
<h2>Don't have an account yet?</h2>
<?php echo $form->create('Member', array('action' => 'register')); ?>
<?php echo $form->input('first_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('last_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->input('psword_confirm' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Confirm'),
'div' => array('style' => ''),
'type' => 'password'
))?>
<?php echo $form->end('Sign In');?>
</div>
I believe your problem is here:
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
The validation errors are designed to show on the form, underneath the appropriate field. However, instead of continuing and trying to display the form, you are redirecting the user to a different page.
If you remove the two lines above, it should show the validation errors beneath their fields on the form when the validation fails.

Resources