<?php

/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace home\actions;

use common\components\Tool;
use Yii;

/**
 * 前台公用的新增动作类
 * 
 * @author Strief http://blog.u-bo.com
 * @since 0.1
 */
class Create extends \yii\base\Action
{

    /**
     * @var class 当前操作所属模型
     */
    public $model;

    /**
     * @var string 当前操作视图名称
     */
    public $view = 'create';

    /**
     * @var string 成功提示信息
     */
    public $successMsg = '新增成功';

    /**
     * @var string 模型的场景 
     */
    public $scenario = 'default';

    /**
     * @var string 当前操作所渲染的布局 
     */
    public $layout;

    /**
     * @var array 要跳转的页面
     */
    public $to;

    public function run()
    {
        $this->model === null && $this->model = $this->controller->model;
        $this->model = new $this->model(['scenario' => $this->scenario]);
        $from = '';
        if($this->model->load(Yii::$app->request->post())){
            $from = Yii::$app->request->post('from');
            if($this->model->save()){
                Yii::$app->getSession()->setFlash('success', $this->successMsg);
                //return $this->controller->flash(['url' => [$this->controller->id.'/create']]);
                $this->model = new $this->model(['scenario' => $this->scenario]);
                /*
                  if (!empty($from)) {
                  return Yii::$app->getResponse()->redirect($from);
                  }
                  elseif (!empty($this->to)) {
                  return $this->controller->redirect($this->to);
                  }
                 */
            } elseif($this->model->hasErrors()){
                $firstError = reset($this->model->getFirstErrors());
                Yii::$app->getSession()->setFlash('error', $firstError);
            }
        }
//		\common\components\Tool::dump($this->model);
        //修改当前动作的布局
        if($this->layout !== null){
            $this->controller->layout = $this->layout;
        }
//        Tool::dump($_POST);
        return $this->controller->render($this->view, [
                    'model' => $this->model,
                    'action' => [$this->controller->id . '/create'],
                    'to' => $this->to,
                    'from' => $from,
        ]);
    }

}
