CakePHP:访问表单助手的“当前”提供给 $form->create() 的模型
在我的 CakePHP 1.3 应用程序中,我需要一个表单控件:
- 由多个表单元素组成,并且
- 可在多个表单中重用。如果可以的话,我想避免代码重复。
因此,我正在创建一个输出表单控件的元素,但在使用编辑操作的值填充控件时遇到了障碍。现在,当您使用默认字段类型时,CakePHP 会为您执行此操作,但在本例中我需要从 $this->data
中获取信息并自己执行此操作。
问题是 $this->data
看起来像这样:
array(
'Model' => array( /* fields from Model */ ),
'AnotherModel' => array( /* fields from AnotherModel */ )
);
在我的可重用元素中,我不知道我的字段属于什么模型。但是,当我调用 $form->create()
(在包含我正在编写的元素的视图中)时,我将此信息告诉了 Form Helper,所以看起来它应该能够告诉我。事实上,FormHelper 类的 API 文档 讲述了 defaultModel 属性,但遗憾的是,这个属性是空的。
现在,简单的解决方案是将模型作为参数传递。我能做到。但是,我想尽可能避免参数膨胀,而且这似乎应该是可能的,但我不知道如何实现。有办法吗?
谢谢!
In my CakePHP 1.3 application, I need a form control that is:
- Comprised of multiple form elements, and
- Reusable in more than one form. I'd like to avoid code duplication if I can.
So, I'm creating an element that outputs my form control, and have hit a roadblock when it comes to populating the control with values on an edit action. Now, when you're using the default field types, CakePHP does this for you, but I need to get information out of $this->data
and do it myself in this case.
The problem is that $this->data
looks like this:
array(
'Model' => array( /* fields from Model */ ),
'AnotherModel' => array( /* fields from AnotherModel */ )
);
Within my reusable element, I don't know what model my field belongs to. However, I told this information to the Form Helper when I called $form->create()
(in the view that includes the element I'm writing), so it seems like it should be able to tell me. And indeed, the API documentation for the FormHelper class tells of a defaultModel
property, but sadly, this property is empty.
Now, the simple solution is to pass the model in as a parameter. I can do that. But, I'd like to avoid parameter bloat where I can, and it seems like this ought to be possible, but I can't figure out how. Is there a way?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
现在我觉得有点不好意思了。我应该在发布之前检查超类。 FormHelper 继承自 AppHelper,而 AppHelper 又继承自 Helper,而 Helper 有一个
model()
方法来完成此任务。吸取教训。 :)
Now I feel a bit sheepish. I should have checked the superclasses before posting. FormHelper inherits from AppHelper, which inherits from Helper, and Helper has a
model()
method that does the trick.Lesson learned. :)
回避这个问题,但另一种选择是子类化 FormHelper 并添加自定义方法来创建控件:
Sidestepping the question, but an alternative would be to subclass the FormHelper and add a custom method to create the control: