【问题标题】:cakephp 3.x create custom widgetcakephp 3.x 创建自定义小部件
【发布时间】:2017-11-11 14:11:08
【问题描述】:

我想为 Cakephp formHelper 创建小部件。

我在 View/Widget 目录中创建了一个名为 ImageWidget.php 的小部件文件(我不知道这是否是正确的目录,但 phpstorm 会加载它,所以看起来不错)

<?php
namespace App\View\Widget;

use Cake\View\Form\ContextInterface;
use Cake\View\Widget\WidgetInterface;

class ImageWidget implements WidgetInterface
{

    protected $_templates;

    public function __construct($templates)
    {
        $this->_templates = $templates;
    }

    public function render(array $data, ContextInterface $context)
    {
        $data += [
            'name' => '',
        ];
        return $this->_templates->format('myTestTemp', [
            'name' => $data['name'],
            'attrs' => $this->_templates->formatAttributes($data, ['name'])
        ]);
    }

    public function secureFields(array $data)
    {
        return [$data['name']];
    }
}
?>

但是我收到了这个错误:

找不到名为“myTestTemp”的模板。

我不知道我应该把我的模板放在哪里,或者这个模板是什么 (和 cakephp 普通模板一样吗?)

我的模板文件是这样的:

//in myTestTemp.ctp file
<p>some html for test</p>

我试图将文件放在这些目录中,但它不起作用

  1. src/模板
  2. src/查看
  3. src/视图/小部件

谢谢

【问题讨论】:

  • 您的问题缺少问题的根源,即您定义使用名为myTestTemp 的(字符串)模板的部分。 ps,无论何时收到错误,请始终发布完成错误,即包括完整堆栈跟踪(理想情况下从日志中以正确可读的方式复制),即使问题对于熟悉 CakePHP 的人来说可能很明显!
  • 对不起,我在复制和粘贴过程中错过了它。感谢您的注意。

标签: cakephp cakephp-3.0


【解决方案1】:

与任何其他小部件一样,您的小部件适用于字符串模板,并且它依赖于在表单助手中设置的模板(分别设置在传递给小部件构造函数的 \Cake\View\StringTemplate 对象上),例如示例:

$this->Form->setTemplates([
    'myTestTemp' => '<p {{attrs}}>some html for test</p>'
]);

另见

【讨论】:

    猜你喜欢
    • 2016-01-18
    • 1970-01-01
    • 2013-01-08
    • 2023-03-20
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 2021-08-16
    相关资源
    最近更新 更多