Cakephp$this-&>数据在提交表单后会丢失大量数据数组 [英] cakephp $this->data loses a LOT of its data array after form submit

查看:0
本文介绍了Cakephp$this-&>数据在提交表单后会丢失大量数据数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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');            
        }   
    }
}

我假设它只返回数组中在我进行编辑时更改过的模型,但是有没有办法强制Cake返回原始的$This->数据?当页面刷新时,我会丢失所有的图像源。也许我不应该进行页面刷新,或者我是否真的需要在控制器中将某种重定向重新定向回相同的页面?

推荐答案

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

$this->data仅由页面上的任何表单域填充。这意味着在您的控制器中,您有几个案例需要处理:

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

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

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库的一部分,它将执行合并已提交数据和完整数据的工作。

这篇关于Cakephp$this-&amp;>数据在提交表单后会丢失大量数据数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆