在CakePHP 3.9中,我可以存储在哪里,如何加载小部件字符串模板?

在CakePHP 3.9中,我可以存储在哪里,如何加载小部件字符串模板?,php,cakephp,widget,cakephp-3.x,Php,Cakephp,Widget,Cakephp 3.x,我想创建一个CakePHP小部件来创建一个自定义表单控件。最终的目标是使它成为一个插件,但现在我正试图确定一个小部件的一般结构。我在src/View/Widget/DateTimeWidget.php中创建了一个包含 <?php namespace App\View\Widget; use Cake\View\Form\ContextInterface; use Cake\View\Widget\WidgetInterface; class DateTimeWidget impleme

我想创建一个CakePHP小部件来创建一个自定义表单控件。最终的目标是使它成为一个插件,但现在我正试图确定一个小部件的一般结构。我在src/View/Widget/DateTimeWidget.php中创建了一个包含

<?php
namespace App\View\Widget;

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

class DateTimeWidget implements WidgetInterface
{

    protected $_templates;

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

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

    public function secureFields(array $data)
    {
        return [$data['name']];
    }
}
?>
然后使用它创建一个表单控件

echo $this->Form->control('end_time', ['type' => 'datetime']);
但是,我遇到了一个错误
找不到名为“DateTime”的模板

我已经创建了基本的模板代码

<?php
$this->Form->setTemplates([
    'DateTime' => '<p {{attrs}}>Test template</p>'
]);

我认为你应该使用单元格


看一看:

我想你应该用电池


看看:

如果您希望小部件附带默认字符串模板,那么您可以在小部件本身中定义它们,方法是将其添加到传递给小部件构造函数的字符串模板实例中。您可以在小部件的
render()
方法中执行此操作,但它在构造函数中无法正常工作,因为小部件实例正在被重用,即它们只被构造一次,例如:

公共函数呈现(数组$data,上下文接口$context)
{
如果(!array\u key\u存在('customDateTime',$this->\u templates->getConfig()){
$this->\u模板->添加([
“customDateTime'=>”测试模板

, // ... ]); } // ... }
另一个选项是将字符串模板放入配置文件中:

//在路径到插件/config/form\u helper\u templates.php中

如果您希望小部件附带默认字符串模板,那么您可以在小部件本身中定义它们,方法是将其添加到传递给小部件构造函数的字符串模板实例中。您可以在小部件的
render()
方法中执行此操作,但它在构造函数中无法正常工作,因为小部件实例正在被重用,即它们只被构造一次,例如:

公共函数呈现(数组$data,上下文接口$context)
{
如果(!array\u key\u存在('customDateTime',$this->\u templates->getConfig()){
$this->\u模板->添加([
“customDateTime'=>”测试模板

, // ... ]); } // ... }
另一个选项是将字符串模板放入配置文件中:

//在路径到插件/config/form\u helper\u templates.php中

我认为DateTime可能是一个非常糟糕的名字,因为它是关键字我认为DateTime可能是一个非常糟糕的名字,因为它是关键字
<?php
$this->Form->setTemplates([
    'DateTime' => '<p {{attrs}}>Test template</p>'
]);