CodeIgniter Forums
Update unchanged entity with "save()" - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Update unchanged entity with "save()" (/showthread.php?tid=86276)



Update unchanged entity with "save()" - Laurent - 01-26-2023

Hi,

I don't understand why I can't update my entity with save() without throwing "DataException::forEmptyDataset" if I open the form and re-submit same values (usual practice).
I don't know if it's a bug or a feature but I don't understand why "by default" it's forbidden ?
(BaseModel.php code seem to volontary doing that by cleaning unchanged datas, lines 1687-1690)

Here is some code :
/**
PHP Code:
    *
    * @param int $user_id
    
*/
    public function test_save(int $user_id)
    {
        $user_model = new \App\Models\UserModel();
        $user $user_model->find($user_id);

        if ($this->request->getMethod() == 'post') {

            $rules = ['nom' => 'required'];

            if ($this->validate($rules)) {

                $postdata $this->request->getPost();
                $postdata array_map('trim'$postdata);
                $user->fill($postdata);

                $user_model->save($user);

                return $this->response->redirect(site_url("test/test_save/" $user_id));
            }
        }

        $data['user'] = $user;
        return view('test/test_user_form'$data);
    

I know I can "try/catch" the unwanted exception or even wrap the "save()" between "if($user->hasChanged())" but I need to understand why I have to.
Can you please explain the idea behind ?

Best regards


RE: Update unchanged entity with "save()" - kilishan - 01-26-2023

I think it was originally designed as a way to alert the developer that they probably missed something. It's caused enough issues for people along the way, though, that there has been discussion around whether it should stay or go. I don't know if a final decision has been made on that yet, though.