如何判断我是否处于编辑或创建之前的保存状态?蛋糕PHP
我有一个模型,需要在保存之前进行一些处理(或在某些情况下进行编辑),但通常在简单编辑时不需要。事实上,如果我对大多数编辑进行处理,结果字段将是错误的。现在,我正在模型的 beforeSave 回调中工作。如何判断我是来自编辑还是添加?
弗兰克·卢克
I have a model where I need to do some processing before saving (or in certain cases with an edit) but not usually when simply editing. In fact, if I do the processing on most edits, the resulting field will be wrong. Right now, I am working in the beforeSave callback of the model. How can I tell if I came from the edit or add?
Frank Luke
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这基本上与 neilcrookes 的答案相同,除了我使用
empty()
作为测试,而不是!isset( )
。如果数组键存在,但为空,则 !isset 将返回 false,而empty 将返回 true。
我喜欢使用相同的视图文件进行添加和编辑,以保持代码干燥,这意味着在添加记录时,“id”键仍将被设置,但不会保留任何内容。 Cake 可以很好地处理这个问题,但 neilcrookes 版本的代码不会将其识别为添加,因为 PrimaryKey 键是在数据数组中设置的(即使它不包含任何内容)。因此,将 !isset 更改为空就可以解决这种情况。
This is basically the same as neilcrookes' answer, except I'm using
empty()
as the test, as opposed to!isset()
.If an array key exists, but is empty, then !isset will return false, whereas empty will return true.
I like to use the same view file for add and edit, to keep my code DRY, meaning that when adding a record, the 'id' key will still be set, but will hold nothing. Cake handles this fine, except neilcrookes version of the code won't recognise it as an add, since the primaryKey key is set in the data array (even though it holds nothing). So, changing !isset to empty just accounts for that case.