Cakephp 3.0 Issue in validation when we use different validation set - validation

I have a custom form for Change Password functionality. But the validations are not properly working on this page.
The template file (change_password.ctp) is:
<div class="users index large-9 medium-8 columns content">
<?= $this->Form->create('change_password') ?>
<fieldset>
<legend><?= __('Change password') ?></legend>
<?= $this->Form->input('old_password', ['type' => 'password', 'label' => 'Old password']) ?>
<?= $this->Form->input('new_password', ['type' => 'password', 'label' => 'Password']) ?>
<?= $this->Form->input('confirm_password', ['type' => 'password', 'label' => 'Repeat password']) ?>
</fieldset>
<?= $this->Form->button(__('Change')) ?>
<?= $this->Form->end() ?>
</div>
The validation code included in a custom function in UsersTable.php page:
public function validationChangePassword(Validator $validator) {
$validator
->requirePresence('old_password', 'create')
->notEmpty('old_password');
$validator
->requirePresence('new_password', 'create')
->notEmpty('new_password');
$validator
->notEmpty('confirm_password')
->add('confirm_password', 'no-misspelling', [
'rule' => ['compareWith', 'new_password'],
'message' => 'Passwords are not equal',
]);
return $validator;
}
I included the changePassword() action in the controller UsersController.php
public function changePassword() {
$user = $this->Users->newEntity();
if (isset($this->request->data) && !empty($this->request->data)) {
$user = $this->Users->patchEntity($user, $this->request->data, [
'validate' => 'changePassword'
]);
if ($user->errors()) {
$this->Flash->success(__('Error'));
}
}
}

Update your action as below:
public function changePassword() {
$user = $this->Users->newEntity();
if (isset($this->request->data) && !empty($this->request->data)) {
$user = $this->Users->patchEntity($user, $this->request->data, [
'validate' => 'changePassword'
]);
if ($user->errors()) {
$this->Flash->success(__('Error'));
}
}
$this->set(compact('user'));
}

Related

how to ignore ajaxValidation in delete action in yii2?

I have a form like follow
<?php widgets\Pjax::begin(['id' => 'authors', 'enablePushState' => false]) ?>
<?php $form = ActiveForm::begin(['id' => $model->formName(),'enableAjaxValidation'=>true,'validationUrl'=>\yii\helpers\Url::toRoute(['paper-author/validation']), 'options' => ['data-pjax' => '']]); ?>
<?php echo $form->field($model, 'FirstName')->textInput()->input('string', ['placeholder' => Yii::t('app', ' FirstName...')])->label(false) ?>
<?php echo $form->field($model, 'LastName')->textInput()->input('string', ['placeholder' => Yii::t('app', ' LastName...')])->label(false) ?>
<?= Html::submitButton('Save', ['class' => 'btn btn-success', 'id' => 'btn1']) ?>
$widget = Yii::createObject([
'class' => 'yii\grid\GridView',
'dataProvider' => $dataprovider,
'columns' => [
'FirstName',
'LastName',
[
'class' => 'yii\grid\ActionColumn',
]
],
]
);
echo $widget->run();
<?php $form = ActiveForm::end(); ?>
<?php widgets\Pjax::end() ?>
and in my model I have some rules:
[['FirstName', 'LastName'],'required']
my controller:
public function actionValidation()
{
$model = new PaperAuthor();
$requestPost = Yii::$app->request->post();
if (Yii::$app->request->isAjax && $model->load($requestPost)) {
Yii::$app->response->format = 'json';
return ActiveForm::validate($model);
}
}
public function actionDelete($id)
{
$this->findModel($id)->delete();
echo Json::encode([
'success' => true,
'messages' => [
Yii::t('app', 'Successfully Deleted.')
],
]);
}
actionCreate works well. but I can't delete any recored from gridview, it throws an validation error(required validation).
what can I do?
thanks in advance.

Yii2 Adding rules in models if the record is already exists in database

My problem is validating the records if already exists in database. So i created a Officials Form using Gii Generator in yii2. It contains name_id,position,fname,mname,lname. If the admin wants to create a new data, and that data is already exists it will show a pop-up message "This data already exists".
How can i achieve that? Any ideas?
This is my model:
class Name extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'name';
}
public function rules()
{
return [
[['position', 'fname', 'lname'], 'required'],
[['position', 'fname', 'mname', 'lname'], 'string', 'max' => 50],
];
}
public function attributeLabels()
{
return [
'name_id' => 'Name ID',
'position' => 'Position',
'fname' => 'First Name',
'mname' => 'Middle Name',
'lname' => 'Last Name',
];
}
}
This is my controller:
public function actionCreate()
{
$model = new Name();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['report/create', 'id' => $model->name_id]);
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
And this is my _form:
<div class="name-form">
<?php yii\widgets\Pjax::begin(['id' => 'sign-up']) ?>
<?php $form = ActiveForm::begin(['id' => 'form-signup', 'options' => ['data-pjax' => true]]); ?>
<?= $form->field($model, 'position')->textInput(['maxlength' => true,'style'=>'width:500px','placeholder' => 'Enter a Position....']) ?>
<?= $form->field($model, 'fname')->textInput(['maxlength' => true,'style'=>'width:500px','placeholder' => 'Enter a First Name....']) ?>
<?= $form->field($model, 'mname')->textInput(['maxlength' => true,'style'=>'width:500px','placeholder' => 'Enter a Middle Name....']) ?>
<?= $form->field($model, 'lname')->textInput(['maxlength' => true,'style'=>'width:500px','placeholder' => 'Enter a Last Name....' ]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-success','style' => 'padding:10px 60px; width:100%;']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php yii\widgets\Pjax::end() ?>
So i assume you want a unique validator, you can try this in your model :
public function rules()
{
return [
[['position', 'fname', 'lname'], 'required'],
[['position', 'fname', 'mname', 'lname'], 'string', 'max' => 50],
[['fname','lname'], 'unique', 'targetAttribute' => ['fname', 'lname'], 'message' => 'This data already exists']
];
}
The above rules will make the combination of fname and lname attributes to be unique, you can modify what attribute or combination of attributes you want to be unique by adding or removing the field name / attributes to the validation rules.
You can create your custom validation , Take any attribute name and define rule :
public function rules()
{
return [
[['position', 'fname', 'lname'], 'required'],
[['position', 'fname', 'mname', 'lname'], 'string', 'max' => 50],
[['position', 'fname', 'lname'], 'checkUniq'], //add this line
];
}
-> custom function in model :
public function checkUniq($attribute, $params)
{
$user = self::find()->where(['fname'=>$this->fname,'lname'=>$this->lname,'position'=>$this->position])->one();
if (isset($user) && $user!=null)
$this->addError($attribute, 'User already added.');
}

CakePHP 3 : default validation not working

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.

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

cakePHP validation errors not showing

So basically I have a view action in my users controller where the user can modify his information(username,first name, last name, email..) this form sends to another update action which does the saving stuff, problem is that when I submit the form and one or more fields don't meet the validation rules it doesn't show underneath each fields but the data doesn't save and
$this->User->validationErrors
outputs the errors.
my update action (accessed after submiting the form on view.ctp)
view.ctp:
<?php
echo $this->Form->create('User', array(
'inputDefaults' => array(
'div' => 'form-group',
'wrapInput' => false,
'class' => 'form-control'
),
'class' => 'well',
'url'=>array('controller'=>'users','action'=>'update'),
'id'=>'info-form'
));
?>
<fieldset>
<legend>Personal Information</legend>
<?php
echo $this->Form->input('id', array('value' => $userinfo['User']['id']));
echo $this->Form->input('User.username', array(
'label' => 'Username',
'value'=>$userinfo['User']['username']
));
?>
<td><?php echo $this->Form->error('username'); ?></td>
<?php
echo $this->Form->input('User.email', array(
'label' => 'E-mail',
'value'=>$userinfo['User']['email']
));
?>
<?php
echo $this->Form->input('User.fname', array(
'label' => 'First name',
'value'=>$userinfo['User']['fname']
));
?>
<?php
echo $this->Form->input('User.lname', array(
'label' => 'Last name',
'value'=>$userinfo['User']['lname']
));
?>
<?php
echo $this->Form->submit('Update', array(
'div' => 'form-group',
'class' => 'btn btn-success'
));
?>
</fieldset>
<?php echo $this->Form->end(); ?>
update function:
function update() {
$this->autoRender = false;
$this->User->set($this->request->data);
if ($this->request->is('post')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Information updated Successfuly.'), 'alert', array(
'plugin' => 'BoostCake',
'class' => 'alert-success'), 'success');
return $this->redirect('/users/view/' . $this->request->data['User']['id']);
} else {
// $errors = $this->User->validationErrors; var_dump($errors);die;
$this->Session->setFlash(__('An error occured'), 'alert', array(
'plugin' => 'BoostCake',
'class' => 'alert-danger'), 'danger');
return $this->redirect('/users/view/' . $this->request->data['User']['id']);
}
} else {
$this->Session->setFlash(__('Request was not of POST type.'), 'alert', array(
'plugin' => 'BoostCake',
'class' => 'alert-danger'), 'danger');
return $this->redirect('/users/index/');
}
It's because you're redirecting after - that will make it lose the validation warnings.

Resources