1.12. Add One New Article

Although we can edit existing articles, we need to be able to add new ones.

1.12.1. The "Add" 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 actionAdd()
    {
        // get a new default record
        $this->item = $this->_model->blogs->fetchNew();
    
        // did the user click the save button?
        if ($this->_isProcess('save')) {
        
            // look for $_POST['blog'] in the request,
            // and load into the record.
            $data = $this->_request->post('blog');
            $this->item->load($data);
        
            // attempt to save it, and redirect to editing on success
            if ($this->item->save()) {
                $uri = "/{$this->_controller}/edit/{$this->item->id}";
                return $this->_redirectNoCache($uri);
            }
        }
    
        // get form hints from the record
        $this->form = $this->item->newForm();
        
        // turn off http caching
        $this->_response->setNoCache();
    }

This action is very similar to the actionEdit() method, but here we don't attempt to fetch an existing record. Instead, we fetch a new (default) record to work with. The process-check and save are similar as well, but on a successful save, we redirect to the edit action for further editing of the newly-saved article.

[Note] Redirect

Solar page controllers have two methods for redirecting a web request: _redirect() and _redirectNoCache(). The no-cache version makes it so that clicking the back button does not result in a accidental resubmission.

1.12.2. The "Add" View Script

Create a view called add.php for the actionAdd() method.

$ vim Blog/View/add.php

Enter the following code in the new add.php view script.

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

<h2><?php echo $this->getText('HEADING_ADD'); ?></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. It is almost identical to the edit.php view script, except it uses different title and header strings.

You should now be able to browse to http://localhost/index.php/blog/add to add a new article.



Local