about 4 years ago

1.建立Yii專案,設定相關config

參考 建立 Yii 專案

2.為 tbl_user table 建立 model

protected/models/user.php
<?php
class User extends CActiveRecord
{
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
    
    public function tableName()
    {
        return 'tbl_user';
    }
    
    // 驗證都寫在rules method中, 若違反驗證就會丟回model instance.
 public function rules()
    {
        return array(
            array('username, password, email', 'required'), 
        );
    }
}
?>

3.建立 Controller

protected/controllers/UserController.php
  <?php
  class UserController extends Controller
  {
    /*
     * 單數資源的action不用$_GET['id'], 直接在method上定義$id即可
     * error
     * public function actionShow()
     *  $user = User::model()->findByPk($_GET['id']);
     * 
     * correct
     * public function actionShow($id)
     *  $user = User::model()->findByPk($id);
     */
    
    /*
     * TODO use before_filter
     */
    public function actionIndex()
    {
      $users = User::model()->findAll();
      $this->render('index', array('users'=>$users));
    }
    
    public function actionShow($id)
    {
      $user = User::model()->findByPk($id);
      if (!isset($user))
      {
        Yii::app()->user->setFlash('error','Can not find this user');
        $this->redirect(array('index'));
      }
      $this->render('show', array('user' => $user));
    }
    
    public function actionNew()
    {
      $user = new User;
      $this->render('new', array('user' => $user));
    }
    
    public function actionCreate()
    {
      $user = new User;
      if(isset($_POST['User']))
      {
        $user->attributes = $_POST['User'];
        if ($user->save())
        {
          Yii::app()->user->setFlash('success', 'Has Saved.');
          $this->redirect('index');
        }
      }
      Yii::app()->user->setFlash('error', $this->setFlashMessage($user->getErrors()));
      $this->render('new', array('user' => $user));
    }
    
    public function actionEdit($id)
    {
      $user = User::model()->findByPk($id);
      $this->render('edit', array('user' => $user));
    }
    
    public function actionUpdate($id)
    {
      $user = User::model()->findByPk($id);
      if (!is_null($user) && isset($_POST['User']))
      {
        $user->attributes = $_POST['User'];
        if ($user->save())
        {
          Yii::app()->user->setFlash('success', 'Has Saved.');
          $this->redirect(Yii::app()->createUrl('user/edit', array('id' => $user->id)));
        }
      }
      Yii::app()->user->setFlash('error', $this->setFlashMessage($user->getErrors()));
      $this->render('edit', array('user' => $user));
    }
    
    public function actionDelete($id)
    {
      $user = User::model()->findByPk($id);
      $user->delete();
      Yii::app()->user->setFlash('success', 'Delete Success.');
      $this->redirect(Yii::app()->createUrl('user/index'));
    }
  }
?>

4.為每個 action 寫 view

protected/views/user/index.php
  <table>
    <tr>
      <td>ID</td>
      <td>User Name</td>
      <td>Email</td>
      <td></td>
    </tr>
    <?php foreach($users as $user): ?>
      <tr>
        <td><?php echo $user->id ?></td>
        <td><?php echo CHtml::link($user->username, array('user/show', 'id' => $user->id)) ?></td>
        <td><?php echo $user->email ?></td>
        <td>
          <?php echo CHtml::link('Edit', array('user/edit', 'id' => $user->id)) ?>|
          <?php echo CHtml::link('Delete', array('user/delete', 'id' => $user->id), array('onClick'=>'return confirm("Are you sure?");')) ?>
        </td>
      </tr>
    <?php endforeach; ?>
  </table>
protected/views/user/show.php
  Hi! <?php echo $user->username; ?><hr>
  Email : <?php echo $user->email; ?><br>
  Password : <?php echo  $user->password; ?><hr>
  
  INFO<br><hr>
  <?php echo print_r($user); ?>
protected/view/user/new.php
  <div class="form">
    <?php $form = $this->beginWidget('CActiveForm', array('action' => Yii::app()->createUrl("user/create"))); ?>
      <!-- 只要model有寫rules驗證,如果有錯誤訊息就會顯示 -->
      <?php // echo $form->errorSummary($user); ?>
      <div class="row">
        <?php echo $form->label($user, 'username'); ?>
        <?php echo $form->textField($user, 'username');?>
      </div>
      <div class="row">
        <?php echo $form->label($user, 'password'); ?>
        <?php echo $form->textField($user, 'password');?>
      </div>
      <div class="row">
        <?php echo $form->label($user, 'email'); ?>
        <?php echo $form->textField($user, 'email');?>
      </div>
      <div>
        <?php echo CHtml::submitButton('Save'); ?>
      </div>      
    <?php $this->endWidget(); ?>
  </div>
protected/view/user/edit.php
  <div class="form">
    <?php $form = $this->beginWidget('CActiveForm', array('action' => Yii::app()->createUrl("user/update", array('id' => $user->id)))); ?>
      <!-- 只要model有寫rules驗證,如果有錯誤訊息就會顯示 -->
      <?php // echo $form->errorSummary($user); ?>
      <div class="row">
        <?php echo $form->label($user, 'username'); ?>
        <?php echo $form->textField($user, 'username');?>
      </div>
      <div class="row">
        <?php echo $form->label($user, 'password'); ?>
        <?php echo $form->textField($user, 'password');?>
      </div>
      <div class="row">
        <?php echo $form->label($user, 'email'); ?>
        <?php echo $form->textField($user, 'email');?>
      </div>
      <div>
        <?php echo CHtml::submitButton('Save'); ?>
      </div>
    <?php $this->endWidget(); ?>
  </div>

5.共用 function 寫在 Controller.php

controller.php 是所有 controller 父類別。
加入一段 method setFlashMessage($errors)

protected/components/controller.php
  <?php
  /**
   * Controller is the customized base controller class.
   * All controller classes for this application should extend from this base class.
   */
  class Controller extends CController
  {
    /**
     * @var string the default layout for the controller view. Defaults to '//layouts/column1',
     * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
     */
    ...
    ...
    ...
    protected function setFlashMessage($errors)
    {
      if (is_array($errors))
      {
        $newErrorString = '';
        foreach($errors as $key => $values)
        {
          $newErrorString.= $values[0].'<br>';
        }
        return $newErrorString;
      }
      return $errors;
    }
  }
?>

6.在共用的 view 加入flash message

protected/views/layouts/main.php
...
...
<?php if(Yii::app()->user->hasFlash('error')): ?>
    <hr>
        <div class="flash-error">
            Error notice : <br><br>
            <?php echo Yii::app()->user->getFlash('error'); ?>
        </div>
        <hr>
<?php elseif(Yii::app()->user->hasFlash('success')): ?>
    <hr>
        <div class="flash-success">
            <?php echo Yii::app()->user->getFlash('success'); ?>
        </div>
    <hr>
<?php endif; ?>
  
<?php echo $content; ?>
...
...
  

TODO

1.before filter
2.partial view

← Yii CActiveForm 使用 PHP Warning: date(): It is not safe to rely on the system's timezone settings.... →