Validation with JavaScript on Yii - javascript

I want to add some JavaScript validation to my form of password creation.
I have the following as javascript
function Validation(){
var password = document.getElementById('password').value;
var error = document.getElementById('error');
if((/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]+$/).test(password) == false){
error.html('error');
}
}
I have the following code in my _form.php for the user creation
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'users-form',
'htmlOptions'=>array('onsubmit'=>'return Validation()'),
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username',array('size'=>20,'maxlength'=>20)); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<div id="error">
</div>
<?php $this->endWidget(); ?>
Now i do have my script imported and even when i put a simple alert('hello') it doesnt work when i press create.
Also i know the validation wont work properly since i am hashing the password. How i can validate it before it becomes hash.

You can do it two way
1) With form htmlOptions
<?php Yii::app()->clientScript->registerScript('someScript', "
validate = function(){
alert("Your Validation Function");
return false;
}
");
?>
<?php $form=$this->beginWidget('CActiveForm', array(
'id' => 'user-form',
'enableAjaxValidation' => false,
'htmlOptions' => array(
'onsubmit'=>"return validate();",
),
)); ?>
2) With Jquery submit method
<?php Yii::app()->clientScript->registerScript('someScript', "
$('#user-form').submit(function() {
alert("Your validation");
});
");
?>
<?php $form=$this->beginWidget('CActiveForm', array(
'id' => 'user-form',
'enableAjaxValidation' => false,
)); ?>

Related

How to auto refresh div contents contain php variables?

I created a page named queries.php
<?php
require("connection.inc.php");
$query = "SELECT SUM(john), SUM(robert), COUNT(school) FROM election";
$result = mysql_db_query($db, $query, $connection) or
die("query error!");
$data = mysql_fetch_array($result);
$john = number_format($data[0], 0,',','.');
$robert = number_format($data[1], 0,',','.');
$school = $data[2];
$total = $john + $robert;
$remaining_school = 524 - $school;
$percentage_john = round(($john*100/$total),2);
$percentage_robert = round(($robert*100/$total),2);
?>
Then I display the data in display.php
The data displayed well and nothing error, I tried a couple of tricks to auto refresh the container using jquery but failed.
Here is my display.php page:
<?php
include("queries.php");
?>
<div id="totaljohn"> // <--- the div id taken from css layout
<h9>John: <?php echo $john; ?> <br> (<?php echo $percentage_john; ?> %)</h9>
</div>
<div id="totalrobert">
<h9>Robert: <?php echo $robert; ?><br> (<?php echo $percentage_robert; ?> %)</h9>
</div>
<div id="totalboth">
<h4>Total : <?php echo $total; ?> Suara</h4>
</div>
<div id="totalschool">
<h4>Total School attending : <?php echo $school; ?> Schools</h4>
</div>
<div id="remaining_schools">
<h4>Remaining Schools: <?php echo $remaining_school; ?> of 524 schools</h4>
</div>
Everything looks good. Is your database connected? Is your SQL correct? Are there records in the database returned for your query?

Yii GridView Ajax update not working

I have a page that contains CGridView in my app. Users can search data by filling the form and clicking submit button. The search function works, and CGridView successfully updated. The problem is it can't be done through ajax, Yii keep doing it through parameters in URL.
I want to update CGridView through ajax so the URL still nice to look. Here's my code.
View File
<?php
Yii::app()->clientScript->registerScript('search', "
$('.btn-link').click(function(){
$('.section').toggle();
return false;
});
$('.section form').submit(function(){
$('#customer2-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
?>
<?php echo CHtml::link('Advanced Search','#',array('class'=>'btn-link')); ?>
<div class="section" style="display:none">
<?php $this->renderPartial('_search',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'customer2-grid',
'dataProvider'=>$model->search(),
'htmlOptions'=>array('style'=>'font-weight:bold'),
'filter'=>$model,
'columns'=>array(
'NAME',
'BIRTHDATE',
'ADDRESS',
'EMAIL',
array(
'header'=>'Action',
'class'=>'CButtonColumn',
'template' => '{add} {updates}',
'buttons' => array(
'add' => array(
'label' => '',
//'imageUrl' => Yii::app()->request->baseUrl.'/images/icon/add.png',
'url' => 'Yii::app()->createUrl("/goods/create/",array("id"=>$data->ID))',
'options'=>array('class'=>'btn btn-info', 'style'=> 'margin-bottom:2px '),
),
'updates' => array(
'label' => 'Update Profil',
// 'imageUrl' => Yii::app()->request->baseUrl.'/images/icon/update.png',
'url' => 'Yii::app()->createUrl("/customer/update/",array("id"=>$data->ID))',
'options'=>array('class'=>'btn btn-info'),
),
),
),
),
));
?>
Here's my _search.php code
<div class="form-horizontal">
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
)); ?>
<div class="form-group">
<?php echo $form->labelEx($model,'NAME',array('class'=>'col-sm-2 control-label')); ?>
<div class="col-sm-6">
<?php echo $form->textField($model,'NAME',array('size'=>60,'maxlength'=>128,'class'=>'form-control')); ?>
</div>
</div>
<div class="form-group">
<?php echo $form->labelEx($model,'BIRTHDATE',array('class'=>'col-sm-2 control-label')); ?>
<div class="col-sm-6">
<?php echo $form->textField($model,'BIRTHDATE',array('class'=>'form-control')); ?>
</div>
</div>
<div class="form-group">
<?php echo $form->labelEx($model,'ADDRESS',array('class'=>'col-sm-2 control-label')); ?>
<div class="col-sm-6">
<?php echo $form->textField($model,'ADDRESS',array('size'=>60,'maxlength'=>512,'class'=>'form-control')); ?>
</div>
</div>
<div class="form-group">
<?php echo $form->labelEx($model,'EMAIL',array('class'=>'col-sm-2 control-label')); ?>
<div class="col-sm-6">
<?php echo $form->textField($model,'EMAIL',array('size'=>60,'maxlength'=>64,'class'=>'form-control')); ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<?php echo CHtml::submitButton('Search', array('class'=>'btn btn-primary')); ?>
</div>
</div>
<?php $this->endWidget(); ?>
</div><!-- search-form -->
Here's my controller code
public function actionAdmin()
{
$this->layout = '//layouts/column1';
$model=new Customer('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Customer']))
$model->attributes=$_GET['Customer'];
$this->render('admin',array(
'model'=>$model,
));
}
The toggle function in the jQuery works just fine but the update function doesn't work. The sorting function in CGridView works as well. What do I miss here?
Is there any restriction in CSS for jQuery/CGridView? I presume there's something wrong with the CSS Selector
EDIT :
I've found the problem which unexpectedly lies in layout/main.php
I've included three javascript files and one of them causing the error.
<!-- JAVASCRIPTS -->
<!-- Placed at the end of the document so the pages load faster -->
<!-- JQUERY -->
<script src="<?php echo Yii::app()->request->baseUrl; ?>/css/default/js/jquery/jquery-2.0.3.min.js"></script>
<!-- JQUERY UI-->
<script src="<?php echo Yii::app()->request->baseUrl; ?>/css/default/js/jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js"></script>
<!-- BOOTSTRAP -->
<script src="<?php echo Yii::app()->request->baseUrl; ?>/css/default/bootstrap-dist/js/bootstrap.min.js"></script>
After I discarded the first script, everything's fine. However, I don't have idea why. Maybe somebody can explain why. Any explanation will be appreciated. Sorry if this question going out of topic
ok I try to describe common solution
this code exampling with default gii crud generator
let you have model Customer.php generetad with standard gii module
class Customer extends CActiveRecord
{
// ...
public function search() {
return new CActiveDataProvider(
// provider properties
'criteria' => new CDbCriteria(), // searches and filters
'sort' => new CSort(), // ordering
'pagination' => new CPagination(), // pagging
);
}
// also there are exists rules for search scneario
public function rules() {
return array(
// ... some other rules
// rule for scenario search
array('NAME, BIRTHDATE,ADDRESS, EMAIL', 'safe', 'on'=>'search'),
);
}
// ...
}
next we should describe primitive controller
class CustomerController extends CController
{
public function actionIndex()
{
// create model with scenario search
$model = new Customer('search');
// check for incoming filter requests and apply filter
if(isset($_GET['Customer']) {
$model->attributes = $_GET['Customer'];
}
$this->render('index', array('model'=>$model);
}
}
now we have to create simplest view with basic CGridView settings
<?php $this->widget('zii.widgets.grid.CGridView', array(
'provider' => $model->search(),
// this property automatically add search field above each columns
'filter' => $model,
));
try this code. and you no need to invent already existing solution by specifying custom search form, of course if you want to have extended search tools, you have to some hard codding

AJAX validation not firing on tabular input fields

The validation works for the first model on my form, but doesn't work for the Items array of models that are looped through. - this is incorrect now as validation is occuring, but not firing when editing any of the BookingRoom input fields.
I have found that when I re-enter data into a Booking field that has just had data removed(displaying a green background in the input box after putting it back in) ajax validation is fired, but it isn't fired when I click on one of the BookingRoom input fields and edit one of those. I have debugged in Firebug the AJAX response for editing a Booking field and the error messages are sent for any of the BookingRoom fields which are invalid.
Here is my performAjaxValidation function:
protected function performAjaxValidation($model, $items)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='booking-form')
{
//echo CActiveForm::validate($model);
$model = CJSON::decode(CActiveForm::validate($model));
$items = CJSON::decode(CActiveForm::validateTabular($items));
var_dump(CJSON::encode(CMap::mergeArray($model, $items)));
Yii::App()->end();
}
}
Update.php
<?php //Yii::app()->clientScript->registerCoreScript('jquery'); ?>
<?php
/* #var $this BookingController */
/* #var $model Booking */
/* #var $bookingRoom BookingRoom */
$this->breadcrumbs=array(
'Bookings'=>array('index'),
$model->id=>array('view','id'=>$model->id),
'Update'
);
$this->menu=array(
array('label'=>'List Booking', 'url'=>array('index')),
array('label'=>'Create Booking', 'url'=>array('create')),
array('label'=>'View Booking', 'url'=>array('view', 'id'=>$model->id)),
array('label'=>'Manage Booking', 'url'=>array('admin'))
);
?>
<h1>Update Booking <?php echo $model->id; ?></h1>
<?php //$this->renderPartial('_form', array('model'=>$model)); ?>
<div class="form">
<button id="btnAdd" type='btnAdd'>Add</button>
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'booking-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>true, 'enableClientValidation' => true, 'errorMessageCssClass' => 'error'
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary(array($model)); ?>
<div class="row">
<?php echo $form->labelEx($model,'customerId'); ?>
<?php echo $form->textField($model,'customerId'); ?>
<?php echo $form->error($model,'customerId'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'date'); ?>
<?php echo $form->textField($model,'date'); ?>
<?php echo $form->error($model,'date'); ?>
</div>
<table id="tblData">
<tbody>
<?php foreach($items as $i=>$item): ?>
<tr>
<td>
<div>
<?php echo $form->labelEx($item,'Room No'); ?>
<?php echo $form->dropDownList($item, "[$i]roomId", CHtml::listData(
Room::model()->findAll(), 'id', 'id'), array('single'=>'single', 'size'=>1)
); ?>
</div>
</td><td>
<div>
<?php echo $form->labelEx($item,'startDate'); ?>
<?php echo $form->textField($item,"[$i]startDate"); ?>
<?php echo $form->error($item,'startDate'); ?>
</div>
</td><td>
<div>
<?php echo $form->labelEx($item,'endDate'); ?>
<?php echo $form->textField($item,"[$i]endDate"); ?>
<?php echo $form->error($item,'endDate'); ?>
</div>
</td><td>
<div>
<?php echo $form->labelEx($item,'adults'); ?>
<?php echo $form->dropDownList($item, "[$i]adults", array('1'=>'1',
'2'=>'2',
'3'=>'3',
'4'=>'4',
'5'=>'5'), array('single'=>'single', 'size'=>1)
); ?>
</div>
</td><td>
<div>
<?php echo $form->labelEx($item,'children'); ?>
<?php echo $form->dropDownList($item, "[$i]children", array('1'=>'1',
'2'=>'2',
'3'=>'3',
'4'=>'4',
'5'=>'5'), array('single'=>'single', 'size'=>1)
); ?>
</div>
</td>
<td>
<button type='button'>Delete</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
In your Yii view form, declare beginWidget as mentioned below,
<?php
$form = $this->beginWidget('CActiveForm', array(
'id'=>'booking-form', //form-id
'enableAjaxValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
Make sure your model has at least one validation rule for that scenario
public function rules()
{
return array(
array('attribute, attribute1', 'required'),
);
}
For detail information visit below the link
http://knackforge.com/blog/vishnu/yii-how-enable-ajax-form-validation

How to detect a product attribute with Javascript? (Magento)

I have a working solution to a problem where we're replacing all 'Add to Cart' buttons with 'In Store Only' buttons for items that are only available in store. I'm using PHP to detect the attribute and produce HTML that replaces the button.
<?php
//Checks if the "Disable Add to Cart" variable is set to 'Yes':
if(($_product->getAttributeText('No_cart_button')) == "Yes"){
//If set to Yes, tell PHP what to output:
echo "This Product is not available online, please call our representative if you wish to purchase this.";
}
//If set as No, then show the 'add to cart box' as usual.
else {
?>
<?php if (!$this->hasOptions()):?>
<div class="add-to-box">
<?php if($_product->isSaleable()): ?>
<?php echo $this->getChildHtml('addtocart') ?>
<?php if( $this->helper('wishlist')->isAllow() || $_compareUrl=$this->helper('catalog/product_compare')->getAddUrl($_product)): ?>
<span class="or"><?php echo $this->__('OR') ?></span>
<?php endif; ?>
<?php endif; ?>
<?php echo $this->getChildHtml('addto') ?>
</div>
<?php echo $this->getChildHtml('extra_buttons') ?>
<?php elseif (!$_product->isSaleable()): ?>
<div class="add-to-box">
<?php echo $this->getChildHtml('addto') ?>
</div>
<?php endif; ?>
<?php
}
?>
I've been told that Javascript would be a less intrusive way of doing achieving the same result. Am I right in assuming that you would use PHP to insert a class or id into the HTML element and do the rest with Javascript? Detect the id or class --> generate the replacement button?
Thanks!

I can't reload the Captcha of my contact form

I'm creating my web page using Yii. When I created the page, Yii created a form very similar than the following:
<?php
/* #var $this SiteController */
/* #var $model ContactForm */
/* #var $form CActiveForm */
$this->pageTitle=Yii::app()->name . ' - Contact';
$this->breadcrumbs=array(
'Contact',
);
?>
<?php if(Yii::app()->user->hasFlash('contact')): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('contact'); ?>
</div>
<?php else: ?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<p class="note"><?php echo Yii::t('app','Fields with');?> <span class="required">*</span> <?php echo Yii::t('app','are required.');?></p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name'); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email'); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'subject'); ?>
<?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>128)); ?>
<?php echo $form->error($model,'subject'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'body'); ?>
<?php echo $form->textArea($model,'body',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'body'); ?>
</div>
<?php if(CCaptcha::checkRequirements()): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
</div>
<div class="hint"><?php echo Yii::t('app','Please enter the letters as they are shown in the image above.');?>
<br/><?php echo Yii::t('app','Letters are not case-sensitive.');?></div>
<?php echo $form->error($model,'verifyCode'); ?>
</div>
<?php endif; ?>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<?php endif; ?>
In the begining, this form worked, but after that, I improved the web page adding more features. Few minutes ago, I was checking all the page and I saw that the reloaded captcha button didn't work. Now, When I try to reload the captcha, the web page is reloaded and display a empty page with this code:
{"hash1":774,"hash2":774,"url":"\/MyApp\/site\/captcha.html?v=526045d3d1187"}
I tried to search for some similar error in google, but I didn't find anything. To be honest, I don't understand what is happening. I guess that the code that I added in another file of my web page produce this error, but I don't have any idea...I don't understand what means this code.
Please, I need your help!
Someone could help me? THANKS
EDIT:
If I look the source code of the web page on my browser, and I search for "captcha.html", I can see the following code:
<script type="text/javascript">
/*<![CDATA[*/
jQuery(function($) {
jQuery('#yw0').after("<a id=\"yw0_button\" href=\"\/MyApp\/site\/captcha.html?refresh=1 \">Obtenga un nuevo c\u00f3digo<\/a>");
jQuery(document).on('click', '#yw0_button', function(){
jQuery.ajax({
url: "\/MyApp\/site\/captcha.html?refresh=1",
dataType: 'json',
cache: false,
success: function(data) {
jQuery('#yw0').attr('src', data['url']);
jQuery('body').data('captcha.hash', [data['hash1'], data['hash2']]);
}
});
return false;
});
But I didn't find the captcha.html in any place...
EDIT 2:
I found the problem. I added javascript code at the end of the main page of my wep page. I added this:
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/scripts/jquery-ui-1.8.12.custom.min.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/scripts/jquery-photostack.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/scripts/jquery-coin-slider.min.js"></script>
If I remove this code, the captcha can be reload correctly. Please, someone could tell me what I'm doing badly here? Why my javascript code produce this? How can I solve it?
The problem is this code in CCaptcha Yii widget:
jQuery(document).on('click', '$selector', function(){
jQuery.ajax({
...
});
return false;
});
The click listener is on document, instead of the element itself. When you add your script tags after this code, you load a new jQuery version that clears all those listeners on init.
To solve this, use only one jQuery version, preferably Yii included one.
If you really want to replace it, do it the right way, in CClientScript->scriptMap in config, set the value of jquery.js and jquery.min.js keys to the new URL of jQuery.

Categories