更改视图数据数组中的值


changing values from view data array

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

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

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

  • 在控制器中给定值

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

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

我在控制器的数据数组中没有得到字段"delivery_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.'));
        }
    }

变量"delivered_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' => ''
    )
)

)

如果你不使用post来编辑它,你可以在控制器中这样编辑它:

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

您不需要通过POST发送这些数据。你已经在后端有了它。

当并没有任何外部依赖关系(比如currentUserId)时,可以通过对模型的回调来实现这样的行为。

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

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