保存当前帖子并编辑下一个帖子

时间:2013-04-28 09:10:19

标签: cakephp redirect

我正在尝试模拟以下工作方案。在cakephp博客文章的编辑阶段,我需要添加Prev& Next个按钮。当我按Next时,我需要保存当前表单,然后下一篇博文将以编辑模式显示。

在我的编辑表格中,我有:

//form create
echo $this->Html->link('Next', 
    array('controller' => 'posts', 'action' => 'next', $id, $nextId), 
    array('class' => 'btn', 'escape' => false)
  );
//inputs
//form submit

next()中的PostsController方法如下所示:

  <?php
  // ... 
  public function next($id = null, $nextId = null) {
    $this->Post->id = $id;
    if (!$this->Post->exists()) {
        throw new NotFoundException('Invalid id', 'info');
    }
  debug($this->request);
    //if ($this->request->is('post') || $this->request->is('put')) {
        if ($this->Post->save($this->request->data)) {
            $this->Session->setFlash('saved', 'ok');
            $this->redirect(
              array('controller'=>'posts', 
                    'action' => 'edit', 
                    $nextId));
        } else {
            $this->Session->setFlash('cant save', 'error');
        }
    //}
}

乍一看,request->data是空的,我不知道为什么。然后,问题是:我的逻辑是否正常?我可以用这种方法解决我的问题吗?

你能分享一个更好的解决方案吗?

2 个答案:

答案 0 :(得分:1)

@nahri是正确的,因为您没有通过点击上一个或下一个链接提交表单数据。

为了简单起见,您应该在表单中包含多个提交按钮,以确保提交数据,但为其提供适当的名称,以便您可以在控制器中相应地处理请求:

在您的观点中:

echo $this->Form->submit('Next', array('name'=>'next'));
echo $this->Form->submit('Previous', array('name'=>'previous'));

在您的控制器中

if($this->request->is('post') && (isset($this->data['next']) || isset($this->data['previous')) {
    // save post as draft...
    // then redirect 
    if(isset($this->data['next'])){
        $this->redirect(array('action' => 'next'));
    }else{
        $this->redirect(array('action' => 'previous'));
    }
}

上面的代码应该说明您可以通过一种方式实现所需功能的原则 - 您需要为应用程序自定义它。

请记住,您仍然将表单发回,就好像您实际保存它一样(即使是相同的操作),唯一的区别是您的上一个或下一个按钮的存在会附加到表单数据。< / p>

我怀疑如果不按照您希望的方式执行此操作,那么您可能需要将AJAX表单重新发送回服务器,然后使用JavaScript重定向窗口。

答案 1 :(得分:0)

您没有提交表单,这就是$this->request->data为空的原因。

你可以这样做:

$this->Form->create('YourModelName', array('action' => 'next'));

// here you want to include your $next value as a hidden form field
$this->Form->input('next', array('type' => 'hidden', 'value' => $next));

// rest of your form
//..  

$this->Form->end(__('Submit'));

然后,您可以使用控制器中的逻辑来保存数据并重定向到下一个编辑页面。 (该值将在$this->request->data['YourModelName']['next'])。

相关问题