| 1 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
class EditPost extends TPage
|
|
|
4 |
{
|
|
|
5 |
/**
|
|
|
6 |
* Initializes the inputs with existing post data.
|
|
|
7 |
* This method is invoked by the framework when the page is being initialized.
|
|
|
8 |
* @param mixed event parameter
|
|
|
9 |
*/
|
|
|
10 |
public function onInit($param)
|
|
|
11 |
{
|
|
|
12 |
parent::onInit($param);
|
|
|
13 |
// Retrieves the existing user data. This is equivalent to:
|
|
|
14 |
// $postRecord=$this->getPost();
|
|
|
15 |
$postRecord=$this->Post;
|
|
|
16 |
// Authorization check: only the author or the administrator can edit the post
|
|
|
17 |
if($postRecord->author_id!==$this->User->Name && !$this->User->IsAdmin)
|
|
|
18 |
throw new THttpException(500,'You are not allowed to edit this post.');
|
|
|
19 |
|
|
|
20 |
if(!$this->IsPostBack) // if the page is initially requested
|
|
|
21 |
{
|
|
|
22 |
// Populates the input controls with the existing post data
|
|
|
23 |
$this->TitleEdit->Text=$postRecord->title;
|
|
|
24 |
$this->ContentEdit->Text=$postRecord->content;
|
|
|
25 |
}
|
|
|
26 |
}
|
|
|
27 |
|
|
|
28 |
/**
|
|
|
29 |
* Saves the post if all inputs are valid.
|
|
|
30 |
* This method responds to the OnClick event of the "Save" button.
|
|
|
31 |
* @param mixed event sender
|
|
|
32 |
* @param mixed event parameter
|
|
|
33 |
*/
|
|
|
34 |
public function saveButtonClicked($sender,$param)
|
|
|
35 |
{
|
|
|
36 |
if($this->IsValid) // when all validations succeed
|
|
|
37 |
{
|
|
|
38 |
// Retrieves the existing user data. This is equivalent to:
|
|
|
39 |
// $postRecord=$this->getPost();
|
|
|
40 |
$postRecord=$this->Post;
|
|
|
41 |
|
|
|
42 |
// Fetches the input data
|
|
|
43 |
$postRecord->title=$this->TitleEdit->SafeText;
|
|
|
44 |
$postRecord->content=$this->ContentEdit->SafeText;
|
|
|
45 |
|
|
|
46 |
// saves to the database via Active Record mechanism
|
|
|
47 |
$postRecord->save();
|
|
|
48 |
|
|
|
49 |
// redirects the browser to the ReadPost page
|
|
|
50 |
$url=$this->Service->constructUrl('posts.ReadPost',array('id'=>$postRecord->post_id));
|
|
|
51 |
$this->Response->redirect($url);
|
|
|
52 |
}
|
|
|
53 |
}
|
|
|
54 |
|
|
|
55 |
/**
|
|
|
56 |
* Returns the post data to be editted.
|
|
|
57 |
* @return PostRecord the post data to be editted.
|
|
|
58 |
* @throws THttpException if the post data is not found.
|
|
|
59 |
*/
|
|
|
60 |
protected function getPost()
|
|
|
61 |
{
|
|
|
62 |
// the ID of the post to be editted is passed via GET parameter 'id'
|
|
|
63 |
$postID=(int)$this->Request['id'];
|
|
|
64 |
// use Active Record to look for the specified post ID
|
|
|
65 |
$postRecord=PostRecord::finder()->findByPk($postID);
|
|
|
66 |
if($postRecord===null)
|
|
|
67 |
throw new THttpException(500,'Post is not found.');
|
|
|
68 |
return $postRecord;
|
|
|
69 |
}
|
|
|
70 |
}
|
|
|
71 |
|
|
|
72 |
?>
|