Wednesday, December 2, 2009

Any chance to get the ID of a new created record BEFORE I save it to the DB?

Hey,

I have a serious problem, and I need a hint from you guys to solve it!

In one of my controller actions, I have the problem that I need to
create some records , let's say A, B, and C.

The problem is, that record A needs a field from record B, which is
the ID of record B, and which I only can set when record A is saved,
and B is saved. In model C I need some information from the new
created models A and B, which I only have when model A and B are
saved.

As this has to do with a register-process for my app, I need to
validate the data for all models. The problem is, that when model A
passes validation, and get's saved (which is needed to save the other
models) and model B fails, I have a "never used" record of model A in
my database. I need to get around that, because that's like a worst
case for me!

I hope there's any chance to create a record, set this record with the
data I get from my registration form, and use the data for the other
records and save everything at the end of the action when every record
validates!

I know I can check a record for validation by setting the model data
with

$this->Model->set($this->data)

and then

if($this->Model->validates()) {
....save the record(s)
}

But right now I'm only able to do this when I have an edit action and
I set the Model to a specific record with like

$this->Model->id = $id_from_get_parameter_or_so


It would be VERY cool if there is a slight chance that I could create
a new record with current auto-increment id from the database, use
that id for my other models, and at the end when I created all needed
records I'd check every record for validation and if every record is
ok, they all get saved.

If anyone knows how to achieve this, I would be very very happy!

Cheers,

DD

P.S.:

If needed, I can post the code of the whole RequestAction to see if
maybe there's another solution to this...

Check out the new CakePHP Questions site http://cakeqs.org and help others with their CakePHP related questions.

You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php?hl=en

No comments: