在 Kohana/MVC 中处理具有关系的表单
这是我在使用 Kohana 框架时遇到的一个问题,尽管我认为这通常适用于 MVC 框架。
假设我有 2 个对象/模型,一个动物对象和一个农场对象,其中一个动物属于一个农场,而一个农场有很多动物。我有一个用于创建新动物的表格,我想要一个下拉菜单来选择它属于哪个农场。我的问题是如何最好地处理从农场表中获取数据并将其显示在表单中。
以下是我提出的一些可能的解决方案,但我不确定其中任何一个都是最好的方法。另外,我计划使用 Kohana 的 Form helper 库,但这似乎只处理表单的 HTML 渲染:
- 获取 AnimalModel 中的数据,将其传递给控制器,控制器将其传递给表单视图。但是我不确定这是否应该是 AnimalModel 的责任。
- 从 FarmModel 获取数据。我在这里担心的是,某些东西有很多关系,控制器将不得不开始调用很多不同的控制器。
- 将传递给 AnimalModel 中各种表单方法的所有数据存储起来。这还涉及存储类之类的东西,这似乎不应该出现在模型中。
- 编写某种辅助对象/库来存储所有表单数据,并将其保存在模型中,或者可能保存在控制器中。不过,我再次觉得这最终会混合显示和业务逻辑,我很乐意享受这一点。
我在设计时遇到的另一个问题是表单中出现的其他问题,例如验证,以及当我希望表单处于“编辑”模式时该怎么做,并且我需要使用模型中的数据预先填充它。
在 Kohana/MVC 框架中编写处理关系的表单的最佳方法是什么?
This is a question I had about working with the Kohana framework, though I imagine that this is something that could apply to MVC frameworks in general.
Let's say I have 2 objects/models, an animal object and a farm object, where an animal belongs to a farm, and a farm has many animals. I have a form for creating new animals, and I want to have a drop down to select which farm it belongs to. My question is how best to handle getting the data from the farm table and display it in the form.
Here are a few possible solutions I came up with, but I'm not sure any of them are the best approach. also, I planned on using Kohana's Form helper library, but that only seems to handle HTML rendering of the forms:
- Get the data in the AnimalModel, pass it to the controller, which passes it to the form view. However I'm not sure if this should be the AnimalModel's responsibility.
- Get the data from the FarmModel. My concern here is that is something has a lot of relations, the controller is going to have to start calling a lot of different controllers.
- Store all the data that gets passed to the various form methods in the AnimalModel. This would also involve storing things like classes, which seems like it shouldn't be in the model.
- Write some kind of helper Object/Library to store all the form data, and keep it in the Model, or possibly the Controller. Again though, I feel like this would end up with a mixing of display and business logic, which I would like to enjoy.
Another concern I had when designing this is other things that come up with forms, such as validation, and also what to do when I want the form in 'edit' mode, and I need to pre-populate it with data from the Model.
What's the best way to approach writing forms that deal with relations in Kohana/MVC Frameworks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许我错过了你的问题,但你似乎把事情变得过于复杂了。使用农场模型获取所有农场的列表。使用此列表在表单中创建选择。
然后,当您拯救动物时,您就拥有了它所属农场的主钥匙。
你的观点可以做这样的事情
Maybe im missing your question but it seems like you're overcomplicating things. Use a Farm model to get a list of all your farms. Use this list to create a select in your form.
Then when you save your animal you have the primary key for the farm it belongs to.
your view could do somethign like this