[Yii 1]Tổng hợp tất cả ví dụ controller, view, form 2

Post Reply
tthlan
Quản trị viên
Posts: 68
Joined: Tue Aug 23, 2016 8:13 am

[Yii 1]Tổng hợp tất cả ví dụ controller, view, form 2

Post by tthlan » 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

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'),            
        );
    }
}
A small Fun view has a form with inputs, one submit button

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 -->
A Examples controller with action render as the view, after submit and pass validate of the Model, it is redirect to action Index.

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));
    }
}
?>
Enjoy!

p/s : next for the extending this demo on validation on scenarios, custom validation, redirect to the action on controller with parameter, ...

tthlan
Quản trị viên
Posts: 68
Joined: Tue Aug 23, 2016 8:13 am

Re: [Yii 1]Tổng hợp tất cả ví dụ controller, view, form 2

Post by tthlan » Thu Feb 16, 2017 8:10 am

Validation with custom validation on Model, redirect to the action on controller with parameter after submit

Expand Fun Model class
- try others valiatotion http://www.yiiframework.com/wiki/56/ref ... validation
- build custom validation
- hasErros() to check has error
- addError vs addErrors

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', 'FunValidation', 'on'=>'scenario'),
            array('favor_food', 'in',
                'range' => array(0,2,3,4,5),
                'message' => 'Life is not only eat to live ! So flatter ?!<br><i>Try your select again.</i>'),
        );
    }

    public function FunValidation($attribute,$param)
    {
        if (!$this->hasErrors()) { /* if form has error, this will skip*/
            if (empty(trim($this->name)) && empty(trim($this->age))) {
                //$this->addErrors(array('name'=>'','age'=>'Plz input Name and Age!'));
                $this->addErrors(array('Plz input Name and Age!')); /* Set message error on summary */
                $this->addErrors(array('age'=>'','name'=>'')); /* Set error on control attribute */
            }
            else if (empty(trim($this->name)) || empty(trim($this->age))) {
                if (empty(trim($this->name)))
                    $this->addError('name', 'Plz input Name!');
                else if (empty(trim($this->age)))
                    $this->addError('age', 'Plz input Age!');
            }
        }
    }
}
Expand Fun view
- try more others input http://www.yiiframework.com/wiki/48/by-example-chtml

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 -->
Expand Examples Controller
- Apply Validation of Model on scenarios
- important : $model->attributes= $_POST['FunModel'];
- redirect(array('control/action' , 'paramter_name_1' => value_1, 'paramter_name_2' => value_2, [n_parameter=n_value])
- $model->validate() vs $model->validate('scenarios')

Code: Select all

class ExamplesController extends Controller
{
    public function actions()
    {
        return array(
            'do' => 'application.controllers.Read.DoAction',
            'previous' => 'application.controllers.Read.PreviousAction',
            'next' => 'application.controllers.Read.NextAction',
            'find' => 'application.controllers.Read.FindAction',
            'test' => 'application.controllers.Read.TestAction',
        );
    }

    public function actionIndex()
    {
        echo "Submit Sucess!";
    }

    public function actionFunValidForm()
    {
        $model = new FunModel;

        if (isset($_POST['FunModel']))
        {
            //$model->attributes= $_POST['FunModel'];

            /*Validation on scenario*/
            $model->setScenario('scenario');

            /* Put attributes after scenraio before validate */
            $model->attributes= $_POST['FunModel'];

            if ($model->validate('scenario') && $model->validate()) {
                $this->redirect(array('/examples/index','name'=>$model->name,'age'=>$model->age));
            }
            else
            {
                $model->addErrors(array('Total:' . count($model->errors)));
                var_dump($model->errors);
            }
        }
        $this->render('/fun', array('model'=>$model));
    }
}
Enjoy !

Post Reply