cakephp 3.x创建自定义小部件

时间:2017-11-11 14:11:09

标签: cakephp cakephp-3.0

我想为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']];
    }
}
?>

但我收到了这个错误:

  

找不到名为&#39; myTestTemp&#39;。

的模板

我不知道我应该把模板放在哪里或者根本不知道这个模板是什么 (它像cakephp普通模板吗?)

我的模板文件是这样的:

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

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

  1. 的src /模板
  2. 的src /查看
  3. SRC /视图/小工具
  4. 感谢

1 个答案:

答案 0 :(得分:1)

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

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

另见