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

Friday, April 22, 2022

[FIXED] What will happen, if Model::$id will not be cleared by create()?

 April 22, 2022     cakephp, cakephp-2.3     No comments   

Issue

On CakePHPs blog tutorial there will be a post saved by following action:

public function add() 
{
    if ($this->request->is('post')) 
    {
        $this->Post->create();
        if ($this->Post->save($this->request->data)) 
        {
            $this->Session->setFlash(__('Your post has been saved.'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Unable to add your post.'));
    }
}

I not really understand the purpose of $this->Post->create(); described in Cookbook:

[...]it resets the model state for saving new information. It does not actually create a record in the database but clears Model::$id [...]

(Found at Cookbook 2.x)

What will happen, if Model::$id will not be cleared by create();?


Solution

I understand your question to (now) mean:

Can I leave out the create call in this code example:

Yes, yes you can

Model::create resets the model to a consistent state, deleting the data property and resetting the id to null.

This method only does something/anything if the model has been modified; if the model state hasn't been modified, or it's the first called method of an action it won't do anything - but it's a good habit to always call create whenever the existing model state is not relevant to the next model method call, and can prevent unexpected application bugs.



Answered By - AD7six
Answer Checked By - Katrina (PHPFixing Volunteer)
  • 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