Bake element ctp for a view [RESOLVED]


#1

Hi !

I’m currently creating a bake template for generating a simple search form + result list in CakePHP 3.6

i would like to have this kind of structure :

  • Element
    • [ControllerName]
      • form.ctp
      • list.ctp
  • [ControllerName]
    • index.ctp

inside index.ctp i could use
{% element ‘form’ %}
but it’s not what i want …
i would like that bake generate the 2 elements (based on bake element template ?) directly and my template in index would be to call $this-element …etc …

i think i should use the Event for generating the files but i’m not sure it is the right solution

Thx for your help


#2

for whose who seek to know how to do it , i found the time to make this :

in the bootstrap.php of your Theme :

EventManager::instance()->on('Bake.beforeRender.Template.edit', function (Event $event) {

// we should render form_add before
Tools::renderTemplateElement($event, 'form_add');

});

and the source code of the method :

    /**
 * @param Event $event
 * @param $element
 * @return bool
 */
public static function renderTemplateElement(Event $event, $element): bool
{

    /** @var \Bake\View\BakeView $view */
    $view = $event->getSubject();

    $pluginModel = $view->viewVars['modelClass'];
    $plugin = $view->viewVars['plugin'];
    $theme = $view->theme;

    /** @var \Cake\ORM\Table $model */
    $model = TableRegistry::get($pluginModel);

    $modelName = $model->getAlias();
    $connectionName = $model->getConnection()->configName();

    $argv = [
        'cake',
        'bake',
        'template',
        $modelName,
        '../Element/' . $element,
        $element,
        '-p',
        $plugin,
        '-c',
        $connectionName,
        '-t',
        $theme,
        '-f'    // force
    ];

    $runner = new CommandRunner(new Application(rtrim(CONFIG, DS)), 'cake');
    $runner->run($argv);

    // move file to element folder
    $pluginPath = current(App::path('Template', $plugin)); // with slash at the end
    $controllerFolder = $modelName . DS;
    $elementFolder = 'Element' . DS . $modelName . DS;
    $ext = '.ctp';

    $oldFile = $pluginPath . $controllerFolder . $element . $ext;

    $elementObj = new Folder($pluginPath . $elementFolder, true);
    $newFile = $elementObj->path . $element . $ext;

    return rename($oldFile, $newFile);
}

if you have any question, don’t hesitate :slight_smile: