beforeAction / afterSave / 等
on beforeAction
PHP Code复制内容到剪贴板
- public function afterSave($insert, $changedAttributes)
- {
- parent::afterSave($insert, $changedAttributes);
- if($insert) {
- //这里是新增数据
- } else {
- //这里是更新数据
- }
- }
- public function beforeDelete()
- {
- parent::beforeDelete();
- //在这里做删除前的事情
- return true;
- }
- public function beforeSave($insert)
- {
- parent::beforeSave($insert);
- if($insert) {
- //执行添加的情况
- } else {
- //执行更新的情况
- }
- return true;
- }
PHP Code复制内容到剪贴板
- public function beforeAction($action)
- {
- if (in_array($action->id, ["material", "participant", "survey", "survey-detail", "schedule", "schedule-detail", "forum", "sign-manage", "weather", "life"])) {
- $planId = \Yii::$app->request->get("planId");
- if (!$planId) {
- return $this->render('/cnooc/nopic');
- }
- $data = ['plan_id' => $planId, 'unique_code' => \Yii::$app->user->getId()];
- $role = $this->getParticipantRole($data);
- if (!$role) {
- return $this->render('/cnooc/nopic', [
- "role" => $role
- ]);
- }
- $this->role = $role;
- $this->appInfo = [
- 'corp_id' => \Yii::$app->config->get("CORP_ID"),
- 'secret' => \Yii::$app->config->get("SECRET_KEY"),
- 'agent_id' => \Yii::$app->config->get("WEIXIN_MEET")['agentId'],
- ];
- }
- return parent::beforeAction($action);
- }
PHP Code复制内容到剪贴板
- /**
- * This is invoked after the record is saved.
- */
- public function afterSave($insert, $changedAttributes)
- {
- parent::afterSave($insert, $changedAttributes);
- Tag::updateFrequency($this->_oldTags, $this->tags,strtolower($this->getClassName()));
- }
PHP Code复制内容到剪贴板
- // 发布新文章后(摘要为空的话根据内容生成摘要)
- public function afterSave($insert, $changedAttributes)
- {
- parent::afterSave($insert, $changedAttributes);
- $article = Article::findOne(['id' => $this->id]);
- if (!emptyempty($article)) {
- if (emptyempty($article->description)) {
- $article->description = $this->generateDesc($this->getProcessedContent());
- $article->save();
- }
- }
- }
PHP Code复制内容到剪贴板
- public function afterDelete() {
- // delete dependencies
- Yii::$app->db->createCommand("DELETE FROM {{%banner_image}} WHERE banner_id=".$this->cacheId)->execute();
- parent::afterDelete();
- }
PHP Code复制内容到剪贴板
- /**
- * 递归删除子分类
- */
- public function afterDelete()
- {
- $ids = $this->getChildrenIds($this->id);
- self::deleteAll(["in","id",$ids]);
- parent::afterDelete();
- }
- public function getChildrenIds($categoryId)
- {
- $ids = '';
- $res = self::find()->where(["pid" => $categoryId])->all();
- if ($res) {
- foreach ($res as $val) {
- $ids .= $val['id'] . ',';
- $ids .= $this->getChildrenIds($val['id']);
- }
- }
- return $ids;
- }
model中添加钩子函数
PHP Code复制内容到剪贴板
- public function beforeSave($insert)
- {
- parent::beforeSave($insert); // TODO: Change the autogenerated stub
- $parent_id = $this->parent_id;
- if ($parent_id) {
- $parent = self::findOne($parent_id);
- if ($parent) {
- // 如果有父级,节点层级加1
- $this->level = ($parent->level += 1);
- } else {
- throw new Exception("父级节点不存在");
- //$this->addError($attribute, '父级节点不存在');
- }
- }
- return true; // TODO: Change the autogenerated stub
- }
控制器中加try ... catch捕捉异常
PHP Code复制内容到剪贴板
- /**
- * 添加资料树节点
- * @return DocumentTree
- * @throws HttpException
- */
- public function actionCreate()
- {
- $post = Yii::$app->request->post();
- $model = new DocumentTree();
- $model->load($post, "");
- try{
- $model->save();
- }catch (Exception $e){
- p($e->getMessage());
- }
- return $model;
- }
PHP Code复制内容到剪贴板
- /**
- * 递归删除子分类
- */
- public function afterDelete()
- {
- $ids = $this->getChildrenIds($this->id);
- self::deleteAll(["in","id",$ids]);
- parent::afterDelete();
- }
- public function getChildrenIds($categoryId)
- {
- $ids = [];
- $res = self::find()->where(["pid" => $categoryId])->all();
- if ($res) {
- foreach ($res as $val) {
- $ids[] = $val['id'];
- $ids = array_merge($ids,$this->getChildrenIds($val['id']));
- }
- }
- return $ids;
- }
PHP Code复制内容到剪贴板
- namespace common\behaviors;
- use common\models\ArticleTag;
- use common\models\Tag;
- use yii\base\Behavior;
- use yii\db\ActiveRecord;
- class TagBehavior extends Behavior
- {
- private $_tags;
- public static $formName = "tagItems";
- public static $formLable = '标签';
- public function events()
- {
- return [
- ActiveRecord::EVENT_INIT => 'initInternal',
- ActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
- ActiveRecord::EVENT_AFTER_UPDATE => 'afterSave',
- ActiveRecord::EVENT_BEFORE_DELETE => 'beforeDelete',
- ];
- }
- public function initInternal($event)
- {
- }
- public function getTags()
- {
- return $this->owner->hasMany(Tag::className(), ['id' => 'tag_id'])
- ->viaTable('{{%article_tag}}', ['article_id' => 'id']);
- }
- public function getTagItems()
- {
- if($this->_tags === null){
- $this->_tags = [];
- foreach($this->owner->tags as $tag) {
- $this->_tags[] = $tag->name;
- }
- }
- return $this->_tags;
- }
- public function getTagNames()
- {
- return join(' ', $this->getTagItems());
- }
- public function afterSave()
- {
- if (\Yii::$app->request->isConsoleRequest ) {
- return;
- }
- $data = \Yii::$app->request->post($this->owner->formName());
- if(isset($data[static::$formName])) {
- if(!$this->owner->isNewRecord) {
- $this->beforeDelete();
- }
- if (!emptyempty($data[static::$formName])) {
- $tags = $data[static::$formName];
- foreach ($tags as $tag) {
- $tagModel = Tag::findOne(['name' => $tag]);
- if (emptyempty($tagModel)) {
- $tagModel = new Tag();
- $tagModel->name = $tag;
- $tagModel->save();
- }
- $articleTag = new ArticleTag();
- $articleTag->article_id = $this->owner->id;
- $articleTag->tag_id = $tagModel->id;
- $articleTag->save();
- }
- Tag::updateAllCounters(['article' => 1], ['name' => $tags]);
- }
- }
- }
- public function beforeDelete()
- {
- $pks = [];
- foreach($this->owner->tags as $tag){
- $pks[] = $tag->primaryKey;
- }
- if (count($pks)) {
- Tag::updateAllCounters(['article' => -1], ['in', 'id', $pks]);
- }
- Tag::deleteAll(['article' => 0]);
- ArticleTag::deleteAll(['article_id' => $this->owner->id]);
- }
- }
afterFind 在asArray 不执行
PHP Code复制内容到剪贴板
- public function afterFind()
- {
- parent::afterFind();
- echo "<PRE>";
- echo var_dump($this);
- echo "</PRE>";
- die();
- }
在config中添加on beforeAction
PHP Code复制内容到剪贴板
- 'on beforeAction' => function ($event) {
- $moduleId = \Yii::$app->controller->module->id;
- $controllerId = Yii::$app->controller->id;
- $actionId = Yii::$app->controller->action->id;
- if ($actionId == "login" || $actionId == "logout") {
- return true;
- }
- if($moduleId == "invest"){
- // 投资管理模块直接放行
- return true;
- }
- if ($controllerId == "site" && $actionId == "index") {
- return true;
- }
- if ($actionId == "choose-project") {
- return true;
- }
- if (!isset($_COOKIE['current_project_id']) || !$_COOKIE['current_project_id']) {
- $url = Url::to(['/invest/contract-project/choose-project']);
- Yii::$app->response->redirect($url);
- Yii::$app->response->send();
- }
- },
PHP Code复制内容到剪贴板
- // 静态方法:
- 'on beforeAction' => [common\components\WxComponent::className(),'getUser'],
- // 公共方法:
- 'on beforeAction' => [new \common\components\WxComponent(),'getUser'], //这里之前一个坑就是构造函数报错
- 'on afterAction' => function ($event) {
- $wxComponent = new common\components\WxComponent();
- return $wxComponent->user;
- },
上一篇 yii2.0 分页
下一篇 yii2 Asset 资源管理