On Wed, Dec 7, 2011 at 9:35 AM, AD7six <andydawso...@gmail.com> wrote: > > > On Dec 3, 7:43 pm, Matteo Landi <landima...@gmail.com> wrote: >> Hi everybody, >> is there a way, given an id, to invoke Model->save() (or anything >> else) to update the relative record if and only if the id is valid? > > yes, you only call save if the id exists. Use exists or if you prefer > count to check. > >> Imagine I want to edit a Post and change its body; if I erroneously >> call the edit action passing an id which does not exist, >> Model->save($data) will create a new Post with the wrong id. > > As someone else has already pointed out if you use bake to generate > your code that cannot happen. > >> >> The following is the implementation of the edit action (very similar >> to the add one): >> >> // controller >> public edit() { >> ... >> $data = validateInput(...); > > why are you validating in the controller? Or does validateinput do > something different than data validation? > >> if ($this->Post->save($data)) >> // ok >> else >> // something went wrong >> ... >> >> } > > which version of cake are you using - the above looks like you're > probably using 1.3
I'm using with 2.0 but I started developing with CakePHP a couple of months ago; anyway, why are you asking this? Do you see something wrong in the action logic presented above? > >> >> What is the right way to avoid this? > > using bake, or referring to an example generated that used bake, such > that your edit action only generates an error if the id doesn't exist. bake or not bake, error or not error, we arrived to the conclusione that I have to validate the id before invoking Model->save(); I think I will put that logic inside the beforeSave callback in order to keep controllers as simple as possible. Regards, Matteo -- http://www.matteolandi.net/ -- Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions. To unsubscribe from this group, send email to cake-php+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php