CakePHP Bake templates controller

527 views Asked by At

I'm creating a custom bake template and I'd like to fetch DB table column type, and comments on a controller file location: Template\Bake\Element\Controller\index.twig, when I'm using code {% set fields = Bake.filterFields(fields, schema, modelObj) %} which I've found on a file Template\Bake\Element\form.twig, it is returning errors showing fields, schema are NULL.

Can someone please assist how I can fetch DB table column type, and comments on a controller file? Since I want to add a FIELDS ARRAY in a recordSet generated by Bake command.

CakePHP v3.8.2 and Bake v1.x

Thanks.

1

There are 1 answers

0
ndm On

The Controller command doesn't set the schema or its columns for the view, you'd have to obtain that on your own via the table object (modelObj), either inside of your template:

{% set schema = modelObj.getSchema() %}
{% set fields = schema.columns() %}
{% set fields = Bake.filterFields(fields, schema, modelObj) %}

or by using an event listener for the Bake.beforeRender.Controller.controller event, which is being dispatched before a controller template is being rendered, and will allow you access to the view and its variables:

// in config/bootstrap_cli.php

use Cake\Event\Event;
use Cake\Event\EventManager;

EventManager::instance()->on(
    'Bake.beforeRender.Controller.controller',
    function (Event $event) {
        /** @var \Cake\View\View $view */
        $view = $event->getSubject();

        /** @var \Cake\ORM\Table $table */
        $table = $view->get('modelObj');

        $schema = $table->getSchema();
        $fields = $schema->columns();

        $view->set(compact('schema', 'fields'));
    }
);

See also