PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 11, 2022

[FIXED] CakePHP4 Edit doesnt update record

 March 11, 2022     cakephp, html, model-view-controller, php     No comments   

Issue

Version: 4.2.9

My edit view is populating my inputs with the data, but when I change them and click on save, its not saving but giving me "user has been saved" message.

UsersController.php edit function

    public function edit($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => ['Userdata'],
        ]);
        if ($this->request->is(['post', 'put'])) {
          $user = $this->Users->get($id, [
              'contain' => ['Userdata'],
          ]);
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
        $this->set(compact('user'));
    }

my edit.php

<div class="users form large-9 medium-8 columns content">
    <?php echo $this->Form->create($user) ?>
    <fieldset>
        <legend><?= __('Edit User') ?></legend>
        <?php
            echo $this->Form->control('userdata.Email');
            echo $this->Form->control('userdata.UserName');
            echo $this->Form->control('PasswordHashed', ['type' => 'password']);
        ?>
    </fieldset>
    <?= $this->Form->button(__('save')) ?>
    <?= $this->Form->end() ?>
</div>


Solution

Your update code is not complete, you have omitted the patchEntity method.

public function edit($id = null)
{
    // call query only once
    $user = $this->Users->get($id, [
        'contain' => ['Userdata'],
    ]);
    // Call the debug method just to test and understand your data
    // debug($user);
    // debug($this->getRequest()->getData()); // debug posted data
    if ($this->request->is(['post', 'put'])) {
      $user = $this->Users->patchEntity($user, $this->getRequest()->getData());
        // debug patched data debug($user); exit;
        if ($this->Users->save($user)) {
            $this->Flash->success(__('The user has been saved.'));

            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The user could not be saved. Please, try again.'));
    }
    $this->set(compact('user'));
}


Answered By - Salines
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing