包含表单的 CakePHP 元素 - 如何使用表关系
我正在尝试创建一个包含表单的元素,以便可以在整个网站中使用它。表单使用的模型与另一个表具有belongsTo关系。在烘焙的添加视图中,我得到了一个很好的 HTML 选择元素,其中包含相关表中的所有值。考虑博客文章并从类别列表中进行选择。
如何创建一个以相同方式工作的元素?
我尝试使用将数据放入元素中
$someVar = $this->requestAction('posts/add');and in the PostsController
... $categories = $this->Post->Category->find('list'); if (isset($this->params['requested'])) { return compact('categories'); } else { $this->set(compact('categories')); }
但我不知道这些数据需要去哪里才能被
echo $this->Form->input('category_id');
我正在使用 CakePHP 2.0,尽管这可能适用于其他版本。
编辑
我就快到了,Oldskool 的答案告诉我这可能是可能的,所以我深入研究了 $this
变量并找到了它应该去的地方。 在视图中,使用:
$this->viewVars = $this->requestAction('posts/add');
并像在烘焙添加视图中一样填充选择元素(即自动)。
I'm trying to create an element that contains a form so it can be used throughout my site. The model used by the form has a belongsTo relationship with another table. In the baked add view I get a nice HTML select element with all the values from the related table. Think of blog posts and selecting from a list of categories.
How can I create an element that works the same way?
I have tried getting the data into the element using
$someVar = $this->requestAction('posts/add');
and in the PostsController
... $categories = $this->Post->Category->find('list'); if (isset($this->params['requested'])) { return compact('categories'); } else { $this->set(compact('categories')); }
but I don't know where this data needs to go so that it is picked up by
echo $this->Form->input('category_id');
I'm using CakePHP 2.0 although this probably applies to other versions.
EDIT
I was nearly there and the answer from Oldskool showed me it was probably possible so I dug into the $this
variable and found where it should go.
In the view, use:
$this->viewVars = $this->requestAction('posts/add');
and the select element is populated as in a baked add view (i.e. automatically).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我自己的蛋糕应用程序之一也有类似的结构。您的方法是正确的,请确保控制器获取您的表单需要了解的数据。在上面的代码中,Cake 应该自动选择它,如果没有,您可以通过将 'options' 键添加到选项数组来“强制”选项,如下所示:
作为故障保护,您可以添加一个检查, 像这样:
I have a similar construction in one of my own Cake apps. Your approach is correct, make sure the controller fetches the data that your form needs to be aware of. In the above code, Cake should automatically pick it up, if it doesn't you can 'force' the options, by adding the 'options' key to the option array, like this:
As a fail-safe you could add a check, like this: