问题
I have two tables, users
and tokens
.
Each user have a activated
field and each token have the {id, token, user_id, created}
fields.
The way the app should work is: On the creation, the app will -
- make sure that the
activated
field is empty (to avoid manipulations to the submitted data). - a token will be created in the
tokens
table.
On update, the app will -
- NOT create a new token.
- NOT allow an update of any kind to the
activated
field. - check if a new email has been submitted, and if so: will create a new token and set the
activated
field to false.
I know how to activate the account through the controller and how to setup the router for that.
What I need is mainly the model configuration.
For example:
I think that the token creation should be done in the afterSave
method, so - how do I determine if the method is called by an update or by a create operation?
Thanks for any help
回答1:
yossi you can also specify the fields that should be saved from the form though - a whitelist of fields it is ok to save in you $this->save() call. That way you can stop a hacker passing an ID in the request, and you should just set it in the controller yourself then with $this->Token->id = whatever you have, I would personally use saveField ('activated) in conjunction with this (just saves a single field!). Fat models is best if you can but get it working first then refactor it if you have got stuck. Better than wasting lots of time writing perfect first time.
回答2:
You question is unclear. If you have a default value for a field, then why not set it in the database rather than doing something in aftersave? If you need to do something that should be done only in certain circumstances, then write a custom method in your model to perform the tasks you want either on creation or update.
Edit
So, if your record has an id, then you know it exists in the database. So, the simple thing to do is (in any method) check to see if the model has an id field and that it is not empty. If it's empty, then you know that you are creating a record and you can do x task. If it isn't, then do y task.
if(isset($modelData['ModelName']['id']) && !empty($modelData['ModelName']['id'])){
//This is an update
} else {
//This is a new record
}
来源:https://stackoverflow.com/questions/7278357/cakephp-creating-new-user-account-several-problems