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

Thursday, December 30, 2021

[FIXED] how to update a single attribute of an item in a table using CakePHP

 December 30, 2021     cakephp, php     No comments   

Issue

I'm trying to update only one piece of information from a user saved in the database, and cakephp accepts an array of values for each attribute, but I don't have values for other attributes and cakephp will not update the row because it is expecting all the values found in the row.


Solution

First Way : Create new a Query object using query():

       $users = TableRegistry::get('Users');
       $query = $users->query();
       $query->update()
       ->set(['is_active' => true])
       ->where(['id' => $id])
       ->execute();

http://book.cakephp.org/3.0/en/orm/query-builder.html


Second Way: Using PatchEntity


using the fieldList() option when creating or merging data into an entity:

this will allow you to only update or insert field u want

         $user = $this->Users->get($id);
         if ($this->request->is(['post', 'put'])) {

            //assume $this->request->data Contains field as ['name' => 'myname', 'title' => 'Hacked!'];

            $user = $this->Users->patchEntity($user, $this->request->data, [
                  'fieldList' => ['title']]);
             // Only allow title to be changed

            if ($this->Users->save($user)) {
                $this->Flash->success(__('Your user has been updated.'));
                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('Unable to update your user.'));
        }

http://book.cakephp.org/3.0/en/orm/saving-data.html#changing-accessible-fields

http://book.cakephp.org/3.0/en/orm/query-builder.html#updating-data



Answered By - Pradeep
  • 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