cakephp $ this->数据在表单提交后丢失了很多数据数组

时间:2012-03-13 18:58:02

标签: cakephp cakephp-2.0 cakephp-appmodel

我有一个manage_photos页面,其$ this->数据包含有关其单位的大量信息。我有一个表单,可以在数据库中进行适当的更改。但是,在提交表单后,$ this->数据(如使用pr($ this->数据)时所见)在页面刷新后会丢失大部分数组数据。以下是我视图中的表单代码:

echo $this->Form->create('Unit', array(
    'action' => 'manage_photos',
    'type' => 'file',
    'inputDefaults' => array(
        'label' => false,
        'div' => false
        )
    )
);
echo $this->Form->hidden('id');
$count=0;
foreach($this->data['Image'] as $img) {
echo '<div class="grid_4 manage-pics">';
echo $this->Form->hidden('Image.'.$count.'.id');
$char_list='http';
$link=strpos($img['img'], $char_list);
if($link===false) {
    echo '<img src="/img/uploaded_img/user/';
    echo $this->data['User']['id'];
    echo "/";
    echo $img['img'];
    echo '" alt=" "  />';
    }
elseif($link!==false) {
    echo '<img src="';
    echo $img['img'];
    echo '" alt="" />';
}
echo '<h4>Picture:  '.$img['img'].'</h4>';
echo '<br />';
echo $this->Form->input('Image.'.$count.'.img_alt', array('label'=>'A description of this picture', 'div'=>true, 'size'=>45));

$count++;
echo '</div>';
}
echo $this->Form->end('Update Photos');?>
<?php echo $this->Session->flash(); ?>

和我的控制器代码:

function manage_photos($id) {
    $this->set('title', 'Edit your photos');
    $this->Unit->id = $id;    
    if (empty($this->data)) {        
        $this->data = $this->Unit->read();    
    } else { 
        if ($this->Unit->saveAll($this->data)) {            
            $this->Session->setFlash('Your photos have been updated.',  'success');            
        }   
    }
}

我认为它只是返回数组中的模型,当我进行编辑时,这些模型已被更改,但有没有办法强制蛋糕返回原始的$ this-&gt;数据?当页面刷新时,我丢失了所有图像src。也许我不应该进行页面刷新,或者我是否需要将某种重定向实际粘贴回控制器中的同一页面?

2 个答案:

答案 0 :(得分:3)

Web和HTTP协议是无状态的。这意味着在Web编程中,默认情况下,请求之间不会保留数据。实际上CakePHP默认启用了会话,可以在很多情况下帮助解决这个问题,但在这里我们可能需要不同的东西。

$this->data仅从您在页面上的任何表单字段中填充。这意味着在您的控制器中您有几种情况需要处理:

  1. GET请求:让我们从数据库加载数据。

  2. POST请求:让我们保存数据

  3. a)成功:重定向到另一个页面或重新加载所有数据。

    b)不成功:让我们从数据库加载所有数据并将其与我们提交的(无效)数据合并以再次显示表单。如果我们不进行合并,用户必须重新键入所有很少需要的更改。

    尝试这样的事情:

    function manage_photos($id) {
        $this->set('title', 'Edit your photos');
        $this->Unit->id = $id;
        if (empty($this->data)) {
            // 1. GET request
            $this->data = $this->Unit->read();
        } else {
            if ($this->Unit->saveAll($this->data)) {
                // 2a POST successful
                $this->Session->setFlash('Your photos have been updated.',  'success');
                $this->data = $this->Unit->read();
            } else {
                // 2b POST unsuccessful
                Set::merge($this->Unit->findById($id), $this->data);
            }
        }
    }
    

    Set::merge()是CakePHP库的一部分,它将把提交的和完整的数据合并在一起。

答案 1 :(得分:-1)

您是否尝试使用Cookie将帖子变量存储到页面刷新或发生错误的情况下?