带参数的子父问题php

问题描述:

这是我在ChildController中使用的一种编辑方法。带参数的子父问题php

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

目前我有一种情况,当我编辑时,'posts'会创建另一条记录。

情景,我已经尝试:

  1. 当我输入这个调用父动作,然后才给了我正确的号码。 $id = $this->request->data['id']; 但是,当它去到父类它消失了,它说它是一个NULL。

  2. 当我在调用父类之后把它删除并且它表示它是一个值'NULL'。

  3. 我也试图把它放在父::行动public function edit($id)return $id;没有运气。 enter code here 我已经尝试过参数ID到父类中的编辑。 很明显,我在父类中做错了什么,但我不知道是什么。

当然,我希望编辑/更新我的应用程序中唯一的一条记录。我究竟做错了什么 ?

在你的父函数中,你根本没有做任何事情的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; 
} 
+0

是的,它的工作。感谢Greg。所以基本上我的错误是,我没有看到$ id默认情况下会进入parent :: edit方法。我将尝试使用Inflector类来操作字符串。 – FortuneSoldier