Hi.
I have a problem with form-validation in Yii framework.
Here is my VIEW code:
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'search-form',
'enableAjaxValidation' => true,
'enableClientValidation' => true,
'focus' => array($model, 'ccc'),
'clientOptions' => array(
'validateOnSubmit' => true,
),
));
?>
<?php
echo $form->errorSummary($model);
?>
<div class="row">
<?php echo $form->labelEx($model, 'input'); ?>
<?php echo $form->textField($model, 'input', array('class' => 'input-medium', 'maxlength' => 11,)); ?>
<?php echo $form->error($model, 'input'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'date'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'attribute' => 'date',
'name' => 'date',
'model' => $model,
'language' => 'ru',
'options' => array(
'dateFormat' => 'dd/mm/y',
'showAnim' => 'slideDown',
'changeMonth' => true,
'changeYear' => true,
'showOn' => 'button',
'constrainInput' => 'true',
),
'htmlOptions' => array(
'style' => 'height:15px; width:6em'
),
));
?>
<?php echo $form->error($model, 'date'); ?>
</div>
<?php $this->endWidget(); ?>
Nothing special. But validation messages working only for textField (Ajax requests are sending only with onChange textField).
How to enable CJuiDatePicker validation messages?
You just have to give the right id to your CJuidatepicker object, use CHtml::getIdByName to create the id value, try to the name of the html element there, it must be something like
'id' => CHtml::getIdByName(get_class($model) . '[' . $attribute . ']')
it would become something like this:
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'id' => CHtml::getIdByName(get_class($model) . '[date]'),
'attribute' => 'date',
'name' => 'date',
'model' => $model,
'language' => 'ru',
'options' => array(
'dateFormat' => 'dd/mm/y',
'showAnim' => 'slideDown',
'changeMonth' => true,
'changeYear' => true,
'showOn' => 'button',
'constrainInput' => 'true',
),
'htmlOptions' => array(
'style' => 'height:15px; width:6em'
),
));
wonde's answer "you should include a value" didn't work for me...
This is what worked:
Yii CActiveForm date validation
views/site/login.php originally had:
$form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
Things worked when this was changed to:
$form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange' => true,
),
See:
http://sky-walker.net/temp/test/yii/testdate/index.php?r=site/login
This is what i did and it works, i think you should include a value
<?php echo $form->labelEx($model,'reportDate'); ?>
<?php $this->widget('zii.widgets.jui.CJuiDatePicker',
array( 'model'=>$model,
'attribute'=>'reportDate',
**'value'=>$model->reportDate,**
'options'=>array(
'showButtonPanel'=>true,
'changeYear'=>true,
'changeMonth'=>true,
'autoSize'=>true,
'dateFormat'=>'yy-mm-dd',
'defaultDate'=>$model->reportDate,
),
));
?>
<?php echo $form->error($model,'reportDate'); ?>
this problem can be shoved simply by adding $form->error($model,'end_date') after CJuiDatePicker.
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'id' => CHtml::getIdByName(get_class($model) . '[date]'),
'attribute' => 'date',
'name' => 'date',
'model' => $model,
'language' => 'ru',
'options' => array(
'dateFormat' => 'dd/mm/y',
'showAnim' => 'slideDown',
'changeMonth' => true,
'changeYear' => true,
'showOn' => 'button',
'constrainInput' => 'true',
),
'htmlOptions' => array(
'style' => 'height:15px; width:6em'
),
));
echo $form->error($model,'dateTo');// added to enaple clint validation
Related
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
Problem in dependent dropdowns when editing in my yii application.
While editing, the drop downs are not automatically selected.
In my view,
array('class' => 'CButtonColumn',
'header' => 'Manage',
'template' => '{update} {view} {delete}',
'htmlOptions' => array('width' => '20%'),
'buttons' => array(
'update' => array(
'label' => '',
'imageUrl' => '',
'options' => array('class' => 'glyphicon glyphicon-pencil'),
),
'view' => array(
'label' => '',
'imageUrl' => '',
'options' => array('class' => 'glyphicon glyphicon-eye-open'),
),
'delete' => array(
'label' => '',
'imageUrl' => '',
'options' => array('class' => 'glyphicon glyphicon-remove'),
),
),
),
<div class="form-group">
<label for="reg_input" class="req">Course</label>
<?php
$course = CHtml::listData(Course::model()->findAll(), 'courseid', 'course_name');
echo CHtml::activeDropDownList($model, 'courseid', $course, array(
'empty' => 'Select Course', 'class' => "form-control",
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('Assignment/Fetchbatch'),
'update' => '#' . CHtml::activeId($model, 'batchid'))));
?>
<?php echo $form->error($model, 'courseid', array('class' => 'school_val_error')); ?>
</div>
<div class="form-group">
<label for="reg_input" class="req">Batch</label>
<?php
$batch = CHtml::listData(Batch::model()->findAll(), 'batchid', 'batch_name');
echo $form->dropDownList($model, 'batchid', $batch, array('prompt' => 'Select Batch',
'class' => "form-control",
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('Assignment/Fetchsubject'),
'update' => '#' . CHtml::activeId($model, 'subjectid'))));
echo $form->error($model, 'batchid', array('class' => 'school_val_error'));
?>
</div>
Second dropdown get the data, to change of first dropdown. At this condition the dropdown will not be selected automatically. Because when editing, that value is not there. So I fixed this problem, my code is above this.
I have already read the forum about make custom cgridview.. I want to make filter use datetimepicker.
Datetimepicker:
I can include already the datetimepicker, but when I choose the date, it became error. :(..
My date datatype on database is 'timestamp'
This is the code
<?php
$this->breadcrumbs=array(
'Events'=>array('index'),
'Manage',
);
$this->menu=array(
array('label'=>'List Event','url'=>array('index')),
array('label'=>'Create Event','url'=>array('create')),
);
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$.fn.yiiGridView.update('event-grid', {
data: $(this).serialize()
});
return false;
});
");
?>
<h1>Manage Events</h1>
<p>
You may optionally enter a comparison operator (<b><</b>, <b><=</b>, <b>></b>, <b>>=</b>, <b><></b>
or <b>=</b>) at the beginning of each of your search values to specify how the comparison should be done.
</p>
<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button btn')); ?>
<div class="search-form" style="display:none">
<?php $this->renderPartial('_search',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php $this->widget('bootstrap.widgets.TbGridView',array(
'id'=>'event-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'afterAjaxUpdate'=>"function(){jQuery('#event_date_search').datepicker({'dateFormat': 'yy-mm-dd'})}",
'columns'=>array(
array(
'type' => 'raw',
'name'=> 'event_image',
'value' => 'CHtml::image("'.Yii::app()->request->baseUrl.'/uploads/event/$data->event_image", "event_image" ,array("width"=>100))',
'filter'=> false,
),
'event_name',
array(
'name' => 'event_date',
'type' => 'raw',
'filter'=>$this->widget('zii.widgets.jui.CJuiDatepicker', array(
'model'=>$model,
'attribute'=>'event_date',
'htmlOptions' => array(
'id' => 'event_date_search'
),
'options' => array(
'dateFormat' => 'yy-mm-dd'
)
), true)
),
array(
'name'=>'published',
'filter'=>CHtml::dropDownList('Event[published]', '',
array(
''=>'',
'1'=>'Published',
'0'=>'Not Published',
)
),
'value' =>'($data->published==1)?"Published":"Not Published"',
),
array(
'class'=>'bootstrap.widgets.TbButtonColumn',
),
),
));
?>
Thank you very much...
You can change search() function of model class. It can be like this:
public function search() {
....
$criteria->addCondition('DATE_FORMAT(time_field, \'%Y-%m-%d\') = ' . $this->time_field);
....
}
but it can be need to translate input value of $this->time_field.
i had the exact same problem yesterday and for some unknown reason by moving the
'dateFormat' => 'yy-mm-dd'
from option to htmloptions fixed my problem. to be honest i have it in both htmloptions and options and don't have any problems so far
'htmlOptions' => array(
'id' => 'event_date_search',
'dateFormat' => 'yy-mm-dd'
),
'options' => array(
'dateFormat' => 'yy-mm-dd'
),
hope this helps
Could you replace your code
'options' => array(
'dateFormat' => 'yy-mm-dd'
)
with
'defaultOptions' => array(
'showOn' => 'focus',
'dateFormat' => 'yy-mm-dd',
'showOtherMonths' => true,
'selectOtherMonths' => true,
'changeMonth' => true,
'changeYear' => true,
'showButtonPanel' => true,
)
Hope this help
For detail check this link http://www.yiiframework.com/wiki/318/using-cjuidatepicker-for-cgridview-filter/
I have a form with required fields, one field is a checkbox. All validation errors will be shown, but no error from checkbox field. I installed DebugKit-Plugin and see, that there will be a validation error, but the message wouldn't shown.
class Users extends AppModel {
public $name = 'Users';
public $validate = array(
'email' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Bitte geben Sie ihre Email-Adresse ein',
'allowEmpty' => false,
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'Diese Adresse ist bereits angemeldet',
),
'email' => array(
'rule' => array('email',true),
'message' => 'Bitte geben Sie eine gültige Email-Adresse ein',
'allowEmpty' => false,
),
),
'terms' => array(
'rule' => array('comparison','!=',0),
'message' => 'Sie müssen unseren Nutzungsbedingungen zustimmen',
'allowEmpty' => false,
),
);
}
Form:
<div class="right text-right" id="register_form">
<?php
echo $this->Form->create('Users', array('action' => 'register', 'inputDefaults' => array()));
echo $this->Form->input('gender', array('label' => 'Anrede: ', 'class' => 'inputField', 'options' => array('m' => 'Herr', 'f' => 'Frau')));
echo $this->Form->input('first_name', array('label' => 'Vorname: ', 'class' => 'inputField'));
echo $this->Form->input('last_name', array('label' => 'Nachname: ', 'class' => 'inputField'));
echo $this->Form->input('email', array('label' => 'Email: ', 'class' => 'inputField'));
echo $this->Form->input('terms', array('div' => true, 'type' => 'checkbox', 'value' => 0, 'label' => false, 'before' => ' <label for="UsersTerms">Ich akzeptiere die '.$this->Html->link('AGB', array('controller' => 'pages', 'action' => 'terms')).' </label>'));
echo $this->Form->submit('Anmelden', array('class' => 'button'));
echo $this->Form->end();
?>
</div>
Controller:
public function register() {
if ($this->Auth->user())
$this->redirect($this->referer('/'));
if ($this->request->is("post")) {
$this->Users->create();
$this->Users->set(Sanitize::clean($this->request->data));
#if ($this->Users->validates())
# die(debug($this->Users->validationErrors));
$this->_hash = $this->Auth->password($this->Users->data['Users']['email']);
$this->_password = $this->__randomString(8, 8);
$this->Users->set('password', $this->Auth->password($this->_password));
if ($this->Users->save()) {
$this->Users->id = $this->Users->getLastInsertID();
$this->_sendActivationMail();
$this->Session->setFlash('An die angegebene Emailadresse wurde soeben ein Aktivierungslink versendet.', 'default', array('class' => 'yellow'));
$this->redirect($this->referer());
} else {
$this->Session->setFlash('Ein Fehler ist aufgetreten', 'default', array('class' => 'red'));
}
}
}
I tried with a "$this->Form->error('terms');" but when I debug this line, in case of error there will be only
<div class="error_message"></div>
CakePHP is last version. Searching since 4 hours for help, but google has no answer. Have you?
Greetings
M.
If anyone has same problem, i could solve mine:
Problem was special char "ü". I tried to save my file with ISO 8859-1 but it needed to save with UTF8. Now error message will be shown.
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.