从视图数据数组中更改值

时间:2014-09-02 07:46:13

标签: php cakephp

我在Model中有一些字段,我想填写控制器(不要让用户输入一些数据..)。例如:curentUserId,或当前日期...... 我找到了2个解决方案。

echo $this->Form->input('delivered_by', array('type' => 'hidden', 'value'=> $_SESSION['id']));
  • 在视图中隐藏字段并为其指定值

$_POST['data']['Sample']['delivered_by'] = 7777777;

  • 在控制器中给出值

  • 如果我在视图中发表评论,例如:

$this->Form->input('delivered_by');

我没有得到现场' deliver_by'在控制器的数据数组中,我无法改变它。

有没有正确/错误的方法? 别人怎么做到这一点? 谢谢, 最好的问候,

这些是控制器的外观:

if ($this->request->is('post')) {


        //$this->request->data['coordinate_x'] = 7777777;   //=>>works with hidden field in view

        $this->Sample->create();
        $this->request->data['Sample']['delivered_by'] = 7;
        debug($_POST);

        if ($this->Sample->save($this->request->data)) {
            $this->Session->setFlash(__('The sample has been saved.'));
            //return $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The sample could not be saved. Please, try again.'));
        }
    }

" deliver_by'没有变化。变量,它保持空白;

array(
'_method' => 'POST',
'data' => array(
    'Sample' => array(
        'task_id' => '3',
        'delivered_by' => '',
        'date_of_delivery' => array(
            'month' => '09',
            'day' => '02',
            'year' => '2014'
        ),
        'sample_label' => '2',
        'coordinate_x' => '2',
        'coordinate_y' => '2',
        'coordinate_z' => ''
    )
)

3 个答案:

答案 0 :(得分:1)

你没有使用帖子用帖子编辑它,你可以在控制器中编辑它:

$this->data['Sample']['delivered_by'] = 77777;

答案 1 :(得分:0)

您无需通过POST发送此数据。你已经把它放在了后端。

当您没有任何外部依赖关系时(例如currentUserId),您可以通过模型上的回调实现此类行为。

当你有外部依赖关系时,你应该决定如何最好地解耦它。

答案 2 :(得分:0)

$sampleData = $this->request->data['Sample'];
$sampleData['delivered_by'] = 7;
if ($this->Sample->save($sampleData)) 
{
       $this->Session->setFlash(__('The sample has been saved.'));
       //return $this->redirect(array('action' => 'index'));
} 
else 
{
    $this->Session->setFlash(__('The sample could not be saved. Please, try again.'));
}