On Dec 3, 7:43 pm, Matteo Landi <[email protected]> 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

>
> 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.

> Should I have to create a helper
> function (like the one below) which validates the id and then update
> the record and then use save inside the add action, and update inside
> the edit one?
>
> // model
> public update($data) {
>     if (!$this->read(null, $data['id']))
>         return;
>     $this->save($data);
>
> }

no

AD

-- 
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
[email protected] For more options, visit this group at 
http://groups.google.com/group/cake-php

Reply via email to