[Yii 1]Tổng hợp tất cả ví dụ controller, view, form 2
Posted: Thu Feb 16, 2017 7:49 am
Note for a small demo to fast understand MVC on Yii 1
A small Fun Model with simple validation, rule require on attributes
A small Fun view has a form with inputs, one submit button
A Examples controller with action render as the view, after submit and pass validate of the Model, it is redirect to action Index.
Enjoy!
p/s : next for the extending this demo on validation on scenarios, custom validation, redirect to the action on controller with parameter, ...
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, ...