无法使用cakephp 3.x中的FormHelper在输入字段中加载默认值

时间:2016-11-15 14:07:47

标签: cakephp-3.0

我面临着一个非常奇怪的任务,即一个非常简单的任务。 我正在尝试使用我的应用程序创建一个非常简单的编辑表单 cakephp 3.x版本。

在我的ContentsController::edit($contentID)方法中,我正在加载要编辑的内容实体

$content = $this->Contents->findById($contentID)->first()

然后我只是使用set()方法创建相应的视图变量:

$this->set('content', $content);

在视图文件中 - 名为edit.ctp - 我所做的只是创建 使用FormHelper使用以下代码的新表单:

<h2><?= __('Edit content: ') . $content->title; ?></h2>
<?php
echo $this->Form->create($content);
echo $this->Form->input('title', ['type' => 'text']);
echo $this->Form->input('alias', ['type' => 'text']);
echo $this->Form->input('body', ['type' => 'textarea']);
echo $this->Form->submit();
?>

以下代码正确创建表单,但它不会从$content实体的每个输入元素中加载默认值。在深入研究FormHelper的源代码之后,我发现在调用FormHelper::create()方法时,它使用EntityContext实体正确加载$content接口。但由于某些原因,我无法解释,在每个FormHelper::input()调用中,上下文接口在内部切换到NullContext,因此没有数据加载到字段中。

有没有人知道我对这段代码做错了什么?

2 个答案:

答案 0 :(得分:0)

也许你可以这样做而不是findById:

$content = $this->Contents->find('all')->where(['id' => $contentID])->first();

答案 1 :(得分:0)

经过多次挖掘后,我找到了问题的真正原因。 FormHelper工作正常,我的查询也是如此。

该问题与视图文件及其呈现方式有关。 整个画面就是这样。

我的观点(edit.ctp)是我创建的常见骨架的扩展,即edit_frm.ctp。所以在我的视图文件中,我通过调用$this->extend('/Common/edit_frm');

来扩展

edit_frm.ctp的结构由三个块组成,如下所示(我删除了html标记)

<?php
// Common/edit_frm.ctp
$this->fetch('formStart');
$this->fetch('formPrimaryOptions');
$this->fetch('formSecondaryOptions');
$this->fetch('formEnd');
?>

现在在我的视图文件(edit.ctp)中,我正在创建这样的块:

<?php
// Contents/edit.ctp
$this->extend('Common/edit_frm');

// The "formStart" block contains the opening of the form
$this->start('formStart');
echo $this->Form->create($content);
$this->end('formStart');

// The "formEnd" block contains the submit button and the form closing tag
$this->start('formEnd');
echo $this->Form->submit();
echo $this->Form->end();
$this->end('formEnd');

// "formPrimaryOptions" contains the main input fields
$this->start('formPrimaryOptions');
echo $this->Form->input('title', ['type' => 'text']);
echo $this->Form->input('alias', ['type' => 'text']);
echo $this->Form->input('body', ['type' => 'textarea']);
$this->end('formPrimaryOptions');
?>

正如您在我的视图文件中看到的那样,我正构建formEnd之前构建formPrimaryOptions块。虽然在我的骨架中,块的输入顺序不同。

CakePHP中的

显然当您在实际视图文件中扩展视图与内容块一起使用时,您必须按照提取的顺序创建块,否则你最终会遇到像我面临的那样奇怪的情况。

无论如何,今天我的课程非常好!!