1.12 添加新文章

尽管现在我们已经可以编辑博客文章了,但是我们还不能添加新文章,这是不能容忍的。

1.12.1 “Add” Action方法

找到并打开Blog.php文件。(在此示例中,我们使用vim编辑器,你可以选择自己最喜欢的)

$ vim Blog.php

在类中添加以下代码:

<?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();
    }

这个Action和actionEdit()方法非常类似,但是这里我们不需要获取一条已存在的记录,我们需要获取的是一条新记录。检查和保存过程也非常类似。但是如果保存成功,页面会被重定向到对刚保存文章的编辑页面。

[Note]重定向

Solar页面控制器有两个方法来处理页面重定向请求:_redirect() 和 _redirectNoCache()。使用无缓存版的方法可以避免因点击后退键而导致的表单意外重复提交。

1.12.2 “Add”视图文件

为actionAdd()方法新建add.php视图文件。

$ vim Blog/View/add.php

在add.php视图文件中添加以下代码:

<?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();
?>

简单地说,这张视图获得表单提示($this->form)并且自动产生表单供用户使用。它和edit.php视图文件几乎是一样的,除了页面的标题和页头信息不同之外。

你现在可以浏览http://localhost/index.php/blog/add来添加新文章了。