We need to be able to edit the existing articles and mark them for publication.
Open the Blog.php
page controller
class file. (In this example we use the vim
editor, but you can use anything you like.)
$ vim Blog.php
Add the following PHP code to the class.
<?php
public function actionEdit($id = null)
{
// was an ID specified?
if (! $id) {
return $this->_error('ERR_NO_ID_SPECIFIED');
}
// fetch one blog article by ID
$this->item = $this->_model->blogs->fetch($id);
// did the blog article exist?
if (! $this->item) {
return $this->_error('ERR_NO_SUCH_ITEM');
}
// did the user click the save button?
if ($this->_isProcess('save')) {
// look for $_POST['blog'] in the request,
// load into the record, and save it.
$data = $this->_request->post('blog');
$this->item->load($data);
$this->item->save();
}
// get form hints from the record
$this->form = $this->item->newForm();
// turn off http caching
$this->_response->setNoCache();
}
Controller, Action, and Process | |
---|---|
We already know about controller classes and action methods. However, an action method may handle different processes, based on which submit button was clicked in a form. The submit button pressed is called the "process" being requested of the action; the value is passed by default as $_POST['process']. |
Some explanation of what's going on in this method:
-
First, we attempt fetch the requested blog article by its ID; if it doesn't exist, we show an error.
-
Next, we look to see if the user has clicked the 'save' button by checking
_isProcess()
. If so, we load the data from $_POST['blog'] into our record, and attempt to save it. -
Finally, we get a set of form hints from the record and retain them in
$this->form
. If the save failed, the form hints will have a series of feedback messages to tell us what went wrong.
Create a view called edit.php
for the
actionEdit()
method.
$ vim Blog/View/edit.php
Enter the following code in the new edit.php
view script.
<?php
$title = $this->getTextRaw('TITLE_EDIT');
$this->head()->setTitle($title);
?>
<h2><?php echo $this->getText('HEADING_EDIT'); ?></h2>
<?php
echo $this->form()
->auto($this->form)
->addProcess('save')
->fetch();
?>
Essentially, this view takes the form hints
($this->form
) and auto-generates a form for the
user to work with.
Where's the Form Code? | |
---|---|
The
However, there are no buttons in the form hints by default. To
remedy this, we add a submit button using the
There are lots of other methods in the
|
You should now be able to browse to http://localhost/index.php/blog/edit/2 and edit the article.