1.13. Delete One Article

We need to be able to delete an existing article.

1.13.1. The "Delete" Action Method

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 actionDelete($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 delete button?
        if ($this->_isProcess('delete')) {
            $this->item->delete();
            $this->_view = 'deleteSuccess';
        }
    }

[Note] Switching Views

By default, a Solar page controller will use a view named for the action. However, you can tell it to use a different view by changing the value of $this->_view.

Some explanation of what's going on in this method:

  • We attempt fetch the requested blog article by its ID; if it doesn't exist, we show an error.

  • Then we look to see if the user has clicked the 'delete' button by checking _isProcess(). If so, we delete the record, and switch to the deleteSuccess view (instead of the default delete view).

That's all there is to it.

1.13.2. The "Delete" View Scripts

This action has two views that it uses: one for displaying the "Are you sure?" page (the default), and one for displaying the "Successfully deleted the record" page.

First, create a view called delete.php ...

$ vim Blog/View/delete.php

... and enter the following code in the new delete.php view script.

<?php
    $title = $this->getTextRaw('TITLE_DELETE');
    $this->head()->setTitle($title);
?>

<h2><?php echo $this->getText('HEADING_DELETE'); ?></h2>

<h3><?php echo $this->escape($this->item->title); ?></h3>

<?php echo $this->nl2p($this->item->body); ?>

<?php echo $this->form()
                ->addProcess('delete')
                ->fetch();
?>

Essentially, this view shows the blog article to be deleted, and presents a standalone form with a single submit button (the 'delete' process).

Next, create a view called deleteSuccess.php ...

$ vim Blog/View/deleteSuccess.php

... and enter the following code in the new deleteSuccess.php view script.

<p><?php echo $this->getText('TEXT_DELETED'); ?></p>

The only thing this view script does is show some static text indicating the record has been deleted.

You should now be able to browse to http://localhost/index.php/blog/delete/3, and click Delete to delete the article.



Local