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

namespace qcbase\actions;

use Yii;

/**
 * 后台公用的更新动作类
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class Update extends \yii\base\Action
{
	/**
	 * @var class 当前操作所属模型 
	 */
    public $model; 
	/**
	 * @var string 当前操作视图名称
	 */
    public $view = 'create';
	/**
	 * @var string 模型的场景 
	 */
	public $scenario = 'default';

 
    public function run()
    {

		$this->model === null && $this->model = $this->controller->model;

		$id = (int)Yii::$app->request->post('id');
		if (empty($id) || !$this->model = call_user_func([$this->model, 'findOne'] ,$id)) {
			Yii::$app->getSession()->setFlash('error', '要更新的对象不存在');
			return $this->controller->flash();
		}
		$this->model->scenario = $this->scenario;
		if ($this->model->load(Yii::$app->request->post())) {
			if ($this->model->save()) {
				Yii::$app->getSession()->setFlash('success', '更新成功');
				return $this->controller->flash(['url' => [$this->controller->id.'/view', 'id' => $id]]);
			}
			/*
			elseif($this->model->hasErrors()) {
				$firstError = reset($this->model->getFirstErrors());
				Yii::$app->getSession()->setFlash('error', $firstError);
				return $this->controller->redirect(['site/flash']);
			}
			*/
		}

        return $this->controller->render($this->view, [
			'model' => $this->model,
			'action' => [$this->controller->id.'/update'],
		]);
    } 
		
}
