/** * Renders form for post editing. * * @param int $id Post ID. * * @throws \EHttpException Thrown if post doesn't exist (404). * @throws \EHttpException Thrown if post wasn't written by current user * (403). * * @return void * @since 0.1.0 */ public function actionEdit($id) { /** @type \Post $model */ $model = \Post::model()->findByPk($id); if ($model === null) { throw new \EHttpException(404); } elseif ((int) $model->user_id !== \Yii::app()->user->id) { throw new \EHttpException(403, 'notAuthorized.postOwnership'); } $data = \Yii::app()->request->getPost('Post'); $categoryData = \Yii::app()->request->getPost('Category'); $failed = false; $category = new \Category(); if ($categoryData) { if (!$category->setAndSave($categoryData)) { $failed = true; } else { $model->category_id = $category->getPrimaryKey(); } } if ($data && !$failed) { $model->setAndSave($data); \Yii::app()->user->sendSuccessMessage('post.update.success', array('{postTitle}' => $model->name)); } $this->pageTitle = $model->name; $url = $this->createUrl('post/show', array('slug' => $model->slug)); $this->page->addNavigationItem($url, 'link.thisPost'); $this->page->resetI18n(array('{postTitle}' => $model->name)); $templateVars = array('post' => $model, 'categories' => \Category::model()->getList(), 'category' => $category); $this->render('form', $templateVars); }
/** * Saves new/existing model via AJAX call. * * @param null|string|int $slug Category slug. * * @throws \EHttpException Thrown if accessed non-ajaxly, no data sent or * model with specified ID doesn't exist. * * @todo update render method(s) to avoid lines of code like the last ones * * @return void * @since 0.1.0 */ public function actionAjaxSave() { if (\Yii::app()->request->isAjaxRequest && (!defined('YII_DEBUG') || !YII_DEBUG)) { throw new \EHttpException(400, 'badRequest.ajaxOnly'); } if (!($data = \Yii::app()->request->getPost('Category'))) { throw new \EHttpException(400, 'badRequest.noDataReceived'); } if (isset($data['id'])) { if (!($category = \Category::model()->findByPk($data['id']))) { throw new \EHttpException(404); } } else { $category = new \Category(); } $response = array('success' => true); if (!$category->setAndSave($data)) { $response['success'] = false; $response['errors'] = $category->getErrors(); } else { $response['data'] = $category->getPublicAttributes(); } $this->page->format = 'json'; header($this->page->generateFormatHeader()); echo \CJSON::encode($response); }