A small Fun Model with simple validation, rule require on attributes
Code: Select all
class FunModel extends CFormModel
{
public $name;
public $age;
public $favor_food;
/**
* Declares the validation rules.
*/
public function rules()
{
return array(
array('name, age', 'required'),
);
}
}
Code: Select all
<?php
$this->pageTitle=Yii::app()->name . ' - Fun Form with Validation';
$this->breadcrumbs=array(
'Fun Valid Form',
);
?>
Welcome Fun with Yii Form !!!!
<div id="fun-form" class="form">
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::errorSummary($model); ?>
<div class="row">
<?php echo CHtml::activeLabel($model,'name'); ?>
<?php echo CHtml::activeTextField($model,'name') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'age'); ?>
<?php echo CHtml::activeTextField($model,'age') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'Favor Food'); ?>
<?php echo CHtml::activeDropDownList($model,'favor_food',array('your-select-plz','none','fish','meat','vegetables','fast-food')) ?>
</div>
<div class="row submit">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php echo CHtml::endForm(); ?>
</div><!-- form -->
Code: Select all
<?php
class ExamplesController extends Controller
{
public function actionIndex()
{
echo "Submit Success!";
}
public function actionFunValidForm()
{
$model = new FunModel;
if (isset($_POST['FunModel']))
{
$model->attributes= $_POST['FunModel'];
if ($model->validate()) {
$this->redirect(array('/examples/index');
}
else
{
$model->addErrors(array('Total:' . count($model->errors)));
var_dump($model->errors);
}
}
$this->render('/fun', array('model'=>$model));
}
}
?>
p/s : next for the extending this demo on validation on scenarios, custom validation, redirect to the action on controller with parameter, ...