Creating EditPost Page
The EditPost page is provided to authors and the administrator to edit existing blog posts. Like the NewPost page, it displays a form to collect the change to the title and content of a post.
We create two files protected/pages/posts/EditPost.page and protected/pages/posts/EditPost.php to save the page template and page class, respectively.
Creating Page Template
The EditPost page template is very similar to the NewPost template. Only the page title and the button caption are different.
<%@ Title="My Blog - Edit Post" %>
<com:TContent ID="Main">
<h1>Edit Post</h1>
<span>Title:</span>
<com:TRequiredFieldValidator
ControlToValidate="TitleEdit"
ErrorMessage="Please provide a title."
Display="Dynamic" />
<br/>
<com:TTextBox ID="TitleEdit" Columns="50" />
<br/>
<span>Content:</span>
<com:TRequiredFieldValidator
ControlToValidate="ContentEdit"
ErrorMessage="Please provide content."
Display="Dynamic" />
<br/>
<com:THtmlArea ID="ContentEdit" />
<br/>
<com:TButton Text="Save" OnClick="saveButtonClicked" />
</com:TContent>
Creating Page Class
The EditPage page class is slightly complex than NewPage because it needs to load the specified post data first. It also needs to perform additional authorization check. In particular, it needs to ensure that a post can only be editted by the author or the administrator. Such authorization check is not provided by PRADO itself.
class EditPost extends TPage
{
@param
public function onInit($param)
{
parent::onInit($param);
$postRecord=$this->Post;
if($postRecord->author_id!==$this->User->Name && !$this->User->IsAdmin)
throw new THttpException(500,'You are not allowed to edit this post.');
if(!$this->IsPostBack)
{
$this->TitleEdit->Text=$postRecord->title;
$this->ContentEdit->Text=$postRecord->content;
}
}
@param @param
public function saveButtonClicked($sender,$param)
{
if($this->IsValid)
{
$postRecord=$this->Post;
$postRecord->title=$this->TitleEdit->SafeText;
$postRecord->content=$this->ContentEdit->SafeText;
$postRecord->save();
$url=$this->Service->constructUrl('posts.ReadPost',array('id'=>$postRecord->post_id));
$this->Response->redirect($url);
}
}
@return @throws
protected function getPost()
{
$postID=(int)$this->Request['id'];
$postRecord=PostRecord::finder()->findByPk($postID);
if($postRecord===null)
throw new THttpException(500,'Post is not found.');
return $postRecord;
}
}
Testing
To test the EditPost page, login first and visit the following URL: http://hostname/blog/index.php?page=EditPost&id=1. This URL can also be reached by clicking on the Edit link on a post detail page.