这是我在ChildController中使用的编辑方法。
public function edit($id = null)
{
parent::edit();
$id = $this->request->data['id'];
$company = $this->Companies->get($id, [
'contain' => []
]);
$this->set(compact('company'));
$this->set('_serialize', ['company']);
}
这就是我在父控制器中使用的方法。
public function edit()
{
$model = $this->getCurrentControllerName();
$editEntity = $this->{$model}->newEntity();
if ($this->request->is(['patch', 'put'])) {
$entityData = $this->{$model}->patchEntity($editEntity, $this->request->data);
if ($this->{$model}->save($entityData)) {
$this->Flash->success(__('The entity has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The entity could not be saved. Please, try again.'));
}
}
}
目前我的情况是,当我编辑时,它会发布'创造了另一条记录。
我已尝试过的情景:
当我在调用父动作之前输入它时,它会给我正确的数字。 $id = $this->request->data['id'];
但是当它进入父类时,它就消失了,它说它是一个NULL。
当我在调用父类之后将其删除时,它只删除它并且它表示它是一个值' NULL'。
我也尝试将它放在parent :: action public function edit($id)
内,而return $id;
则没有运气。 enter code here
我已经尝试将参数ID用于父类中的编辑。
对我来说很明显,我在父母班上做错了什么,但我不知道是什么。
当然,我显然想要编辑/更新我的应用程序中唯一的一条记录。我究竟做错了什么 ?
答案 0 :(得分:2)
在你的父函数中,你没有对ID或现有实体做任何事情,所以难怪它没有像你想要的那样进行更新。
也许是这样的事情?
public function edit($id = null)
{
$company = parent::_edit($id);
if ($company === true) {
return $this->redirect(['action' => 'index']);
}
// If you use the Inflector class, you could even move these lines into _edit,
// and perhaps even eliminate this wrapper entirely
$this->set(compact('company'));
$this->set('_serialize', ['company']);
}
// Gave this function a different name to prevent warnings
// and protected access for security
protected function _edit($id)
{
$model = $this->getCurrentControllerName();
// No need to get the $id from $this->request->data, as it's already in the URL
// And no need to pass an empty contain parameter, as that's the default
$editEntity = $this->{$model}->get($id);
if ($this->request->is(['patch', 'put'])) {
$entityData = $this->{$model}->patchEntity($editEntity, $this->request->data);
if ($this->{$model}->save($entityData)) {
$this->Flash->success(__('The entity has been saved.'));
return true;
} else {
$this->Flash->error(__('The entity could not be saved. Please, try again.'));
}
}
return $editEntity;
}