I need to apply rule on a form. I have a country and dependent drop down of state.
I need to apply required rule on state field.
But if i choose India from drop down then required rule should be remove from the form.
I have enabled clientsidevalidation true in cactiveform.
View form:
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'cart',
'enableAjaxValidation' => false,
'enableClientValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true),
// we need the next one for transmission of files in the form.
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
echo $form->dropDownList($modelUser, 'country', Countries::getcountrylistwithcode(),
array('options' => array($currentCountry=>array('selected'=>true)),
'empty'=>'Select Country',
'class'=>'form-control input-lg',
));
echo $form->error($modelUser,'country');
echo $form->labelEx($modelUser,'state',array('class'=>"col-md-30"));
echo $form->dropDownList($modelUser, 'state', $stateList,array('class'=>"form-control input-lg",'prompt'=>'Select State'));
echo $form->error($modelUser,'state');
$this->endWidget();
?>
And model rules are like this:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('city,country,state,address_line_one,postcode', 'required'),
You can achieve this by adding a custom rule to your model.
Change your rules function to something like this
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('city,country,address_line_one,postcode', 'required'),
array('state', 'validateState'),
)
}
Next up would be to create the custom validation rule. This would look something like this
public function validateState ($attribute, $params)
{
$aCountriesWithState = array('USA');
if (in_array($this->$attribute, $aCountriesWithState) && empty($this->$attribute))
{
$this->addError($attribute, 'State is missing');
}
}
I want to UPDATE record without losing the File that i have uploaded. Below is my create action.
public function actionCreate()
{
$model = new Page;
if (isset($_POST['Page']))
{
$model->attributes = $_POST['Page'];
$model->filename = CUploadedFile::getInstance($model, 'filename');
if ($model->save())
{
if ($model->filename !== null)
{
$dest = Yii::getPathOfAlias('application.uploads');
$model->filename->saveAs($dest . '/' . $model->filename->name);
$model->save();
}
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
In yii, update method is designed to update the values that you are posting from your form. It will not update all Model properties.
For suppose, your Page model has 4 model properties, assume all are mandatory.
title
description
keywords
image
Since you don't want to update image field, you can make it non mandatory field by setting scenario for image field in your Page model rules.
class Page extends CActiveRecord
{
/*
Coding
*/
public function rules()
{
return array(
array('title, description,keywords', 'required'),
array('image', 'file', 'types'=>'jpg, png'),
array('image', 'required', 'on' => 'insert'),
// => You need image field to be entered on Create, not on Update
.................
}
}
So, Show file input in your form on Create, Hide on Update action so that image field won't submit.
//Your page form
<?php if($model->isNewRecord):?>
echo $form->labelEx($model, 'image');
echo $form->fileField($model, 'image');
echo $form->error($model, 'image');
<?php endif;?>
Since your are using Yii-2 you can use skippOnEmpty validator for the same.
I get an error 200. Form never gets posted, all fields return blank. I also checked if the columns are required, i set everything to null. I have another form that looks like this and it works fine. Any ideas?
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'thisForm',
)); ?>
//form
<?php
echo CHtml::ajaxSubmitButton('Add',
Yii::app()->createUrl("url/controller"),
array(
'type'=>'POST',
'dataType'=>'text json',
'data'=>'js:$("#thisForm").serialize()',
'success'=>'js:function(data) {
if(data.status=="success")
$.fn.yiiGridView.update("osb123");
}',
'error'=>'function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}'
));
?>
public function actionController()
{
$model=new Model;
if($_POST['Model'])
{
$model->attributes=$_POST['Model'];
$model->temporary_id = Yii::app()->user->user_id;
$model->cost = floatval($_POST['Model']['cost']);
$model->active = "Y";
if($model->validate()){
echo CJSON::encode(array('status'=> 'success',
'data'=>var_dump($_POST['Model'])
));
}
else{
$error = CActiveForm::validate($model);
echo CJSON::encode(array('status'=> 'error', 'error'=>var_dump($_POST['Model'])));
}
}else echo CJSON::encode(array('status'=>'error','error'=>'Not Set'));
}
In the ajax button for url you set: Yii::app()->createUrl("url/controller") while usually the right syntax is Yii::app()->createUrl("controller/action") Could you with debugging tool (Ctrl+Shift+I or F12) check the POST-request and see the actual url that has been generated by yii?
You have beginWidget, do you also have endWidget ?
I am new in Yii, I am currently trying to do a product page in my local system. I declare DateField as product_availability_date,product_end_date. but when I enter the dates in front end and submit, it again shows me an error to re-enter the dates. please say a solution to this. Thanks in advance.
ProductsController:
<?php
class ProductsController extends Controller
{
/**
* #var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column2';
/**
* #return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view','search'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update','search'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete','search'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Products;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Products']))
{
$model->attributes=$_POST['Products'];
if($model->save())
$this->redirect(array('view','id'=>$model->product_id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Products']))
{
$model->attributes=$_POST['Products'];
if($model->save())
$this->redirect(array('view','id'=>$model->product_id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* #param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Products');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Products('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Products']))
$model->attributes=$_GET['Products'];
$this->render('admin',array(
'model'=>$model,
));
}
//search
public function actionsearch()
{
$model=new Products;
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Products']))
$model->attributes=$_GET['Products'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* #param integer $id the ID of the model to be loaded
* #return Products the loaded model
* #throws CHttpException
*/
public function loadModel($id)
{
$model=Products::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* #param Products $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='products-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
Products model:
<?php
/**
* This is the model class for table "products".
*
* The followings are the available columns in table 'products':
* #property integer $product_id
* #property string $product_name
* #property string $description
* #property integer $quantity
* #property integer $category_id
* #property integer $location_id
* #property string $vendor
* #property string $status
* #property integer $stock
* #property string $prod_avl_date
* #property string $prod_end_date
*/
class Products extends CActiveRecord
{
public $vendor_name;
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'products';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('product_name, description, quantity, category_id, location_id, status, stock', 'required'),
array('quantity, location_id, stock', 'numerical', 'integerOnly'=>true),
array('product_name, vendor', 'length', 'max'=>50),
array('status', 'length', 'max'=>2),
array('prod_avl_date, prod_end_date', 'date','format'=>array('yyyy/MM/dd','yyyy/MM/d')),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('product_id, product_name, description, quantity, category_id, location_id, vendor, status, stock, prod_avl_date, prod_end_date', 'safe', 'on'=>'search'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array('category_id' => array(self::BELONGS_TO, 'Category','category_id'),
'location_id' => array(self::BELONGS_TO, 'Location','location_id'),
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'product_id' => 'Product',
'product_name' => 'Product Name',
'description' => 'Description',
'quantity' => 'Quantity',
'category_id' => 'Category',
'location_id' => 'Location',
'vendor' => 'Vendor',
'status' => 'Status',
'stock' => 'Stock',
'prod_avl_date' => 'Prod Avl Date',
'prod_end_date' => 'Prod End Date',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* #return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('product_id',$this->product_id);
$criteria->compare('product_name',$this->product_name,true);
$criteria->compare('description',$this->description,true);
$criteria->compare('quantity',$this->quantity);
$criteria->compare('category_id',$this->category_id);
$criteria->compare('location_id',$this->location_id);
$criteria->compare('vendor',$this->vendor,true);
$criteria->compare('status',$this->status,true);
$criteria->compare('stock',$this->stock);
$criteria->compare('prod_avl_date',$this->prod_avl_date,true);
$criteria->compare('prod_end_date',$this->prod_end_date,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* #param string $className active record class name.
* #return Products the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
form:
<?php
/* #var $this ProductsController */
/* #var $model Products */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'products-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,
)); ?>
<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,'product_name'); ?>
<?php echo $form->textField($model,'product_name',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'product_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'description'); ?>
<?php echo $form->textArea($model,'description',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($model,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'quantity'); ?>
<?php echo $form->textField($model,'quantity'); ?>
<?php echo $form->error($model,'quantity'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'category_id');
echo $form->dropDownList($model,'category_id', CHtml::listData(Category::model()->findAll(), 'category_id', 'category_name'), array('prompt'=>'Select category','multiple' => 'multiple'));
?>
<?php echo $form->error($model,'category_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'location_id');
echo $form->dropDownList($model,'location_id', CHtml::listData(Location::model()->findAll(), 'location_id', 'location_name'), array('empty'=>'Select location'));?>
<?php echo $form->error($model,'location_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'vendor');
echo $form->dropDownList($model,'location_id',CHtml::listData(Vendor::model()->findAll(location_id),'location_id','vendor_name'),
array(// htmlOptions
'ajax'=>array(// special htmlOption through clientChange, for ajax
'type'=>'GET',
'url'=>$this->createUrl('Vendor/Vendordetails'),// action that will generate the data
'data'=>'js:"id="+$(this).val()',// this is the data that we are sending to the action in the controller
'dataType'=>'json',// type of data we expect back from the server
'success'=>'js:updateFields'// a javascript function that will execute when the request completes successfully
),
)
);
//echo $form->dropDownList($model,'vendor', CHtml::listData(Vendor::model()->findAll(), 'location_id', 'vendor_name'), array('empty'=>'Select vendor'));?>
<?php echo $form->error($model,'vendor'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'status'); ?>
<?php $status=array("AVAILABLE","NOT AVAILABLE")?>
<?php echo $form->radioButtonList($model,'status',$status,array('separator'=>'')); ?>
<?php echo $form->error($model,'status'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'stock'); ?>
<?php echo $form->textField($model,'stock'); ?>
<?php echo $form->error($model,'stock'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'prod_avl_date'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker',array(
'name'=>'prod_avl_date',
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat' => 'yy-mm-dd',
'timeFormat' => 'hh:mm:ss',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<?php echo $form->error($model,'prod_avl_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'prod_end_date'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker',array(
'name'=>'prod_end_date',
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat' => 'yy-mm-dd',
'timeFormat' => 'hh:mm:ss',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<?php echo $form->error($model,'prod_end_date'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
<!-- form -->
problem in name of CJuiDatePicker:
replace
'name'=>'prod_avl_date',
with
'name'=>'Products[prod_avl_date]',
Do same thing for prod_end_date also
Note: You have to set date format in CJuiDatePicker exactly as it is in model rules
'dateFormat' => 'yy/mm/dd',
My front end is Php Yii. I am trying to create a custom validation rule which checks to see if the username already exists in the database.
I don't have direct access to the database. I have to use the RestClient to communicate with the Database. My issue is that custom validation rule is not working with my CFormModel.
Here is my code:
public function rules()
{
return array(
array('name', 'length', 'max' => 255),
array('nickname','match','pattern'=> '/^([a-zA-Z0-9_-])+$/' )
array('nickname','alreadyexists'),
);
}
public function alreadyexists($attribute, $params)
{
$result = ProviderUtil::CheckProviderByNickName($this->nickname);
if($result==-1)
{
$this->addError($attribute,
'This Provider handler already exists. Please try with a different one.');
}
This doesn't seem to work at all, I also tried this:
public function alreadyexists($attribute, $params)
{
$this->addError($attribute,
'This Provider handler already exists. Please try with a different one.');
}
Even then, it doesn't seem to work. What am I doing wrong here?
The problem with your code is that it doesn't return true or false.
Here is one of my rules to help you:
<?php
....
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('title, link', 'required'),
array('title, link', 'length', 'max' => 45),
array('description', 'length', 'max' => 200),
array('sections','atleast_three'),
);
}
public function atleast_three()
{
if(count($this->sections) < 3)
{
$this->addError('sections','chose 3 at least.');
return false;
}
return true;
}
...
?>
I met the same issue and finally got it solved. Hopefully, the solution could be useful for resolving your problem.
The reasons why the customised validation function is not called are:
this is a server side rather than client side validation
when you click the "submit" button, the controller function takes over the process first
the customised function won't be involved if you didn't call "$model->validate()"
Therefore, the solution is actually simple:
Add "$model->validate()" in the controller function. Here is my code:
"valid.php":
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'alloc-form',
'enableClientValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true,),
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'valid_field'); ?>
<?php echo $form->textField($model,'valid_field'); ?>
<?php echo $form->error($model,'valid_field'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
"ValidForm.php":
class ValidForm extends CFormModel
{
public $valid_field;
public function rules()
{
return array(
array('valid_field', 'customValidation'),
);
}
public function customValidation($attribute,$params)
{
$this->addError($attribute,'bla');
}
}
"SiteController.php"
public function actionValid()
{
$model = new ValidForm;
if(isset($_POST['AllocationForm']))
{
// "customValidation" function won't be called unless this part is added
if($model->validate())
{
// do something
}
// do something
}
}