在 CakePHP 的 CRUD 插件中使用单个模板进行编辑和查看方法

问题描述 投票:0回答:0

我有 PHP 经验,但第一次使用 CakePHP 4。

"cakephp/cakephp": "~4.4",   
"friendsofcake/crud": "^6.1.1"

该项目正在使用蛋糕之友CRUD插件。

控制器中已经有一个视图方法和一个关联的 view.php 模板文件。

我想要做的是创建一个编辑方法并使编辑方法使用完全相同的 view.php 文件。我不需要重复的 edit.php 文件,它是 view.php 文件的精确副本。

下面是控制器代码的一部分,您可以在其中看到视图和编辑方法的相关部分

public function view($id)
{

        $this->Crud->on('beforeFind', function (Event $event) {
            $event->getSubject()->query->contain([
                'something', 'somethingOtherThings',
            ]);
        });

        //Some other code
    
        $this->set(compact('fields'));
    
        return $this->Crud->execute();
    }
    
    public function edit($id)
    {
        //some code here and some things I tried below
    
        //$this->viewBuilder()->setTemplate('view'); //1.
    
        //$this->Crud->action()->setConfig('scaffold.view', 'view'); //2.
    
        //$this->render('view'); //3.

        //some other code here
    
        $this->set(compact('fields'));
    
        return $this->Crud->execute();
    }

即使使用一个模板进行查看和编辑是一个坏主意,我仍然想了解并知道如何在控制器中以编程方式使用/打开特定模板。您可以在评论中看到我发现了各种解决方案和建议,但在这种情况下并不起作用。

我尝试调试 Crud 执行方法,当我从编辑方法尝试 1.、2. 或 3. 时,最后的 $view 始终是编辑的。

    public function execute(?string $controllerAction = null, array $args = []): ResponseInterface
    {
        $this->_loadListeners();

        $this->_action = $controllerAction ?: $this->_action;

        $action = $this->_action;
        if (empty($args)) {
            $args = $this->getController()->getRequest()->getParam('pass');
        }

        try {
            $event = $this->trigger('beforeHandle', $this->getSubject(compact('args', 'action')));

            $response = $this->action($event->getSubject()->action)->handle($event->getSubject()->args);
            if ($response instanceof ResponseInterface) {
                return $response;
            }
        } catch (CrudException $e) {
            $response = $e->getResponse();
            if ($response !== null) {
                return $response;
            }

            throw $e;
        }

        $view = null;
        $crudAction = $this->action($action);
        if (method_exists($crudAction, 'view')) {
            $view = $crudAction->view();
        }

        return $this->_controller->render($view);
    }

我尝试在编辑方法中使用以下内容,但没有一个将模板更改为view.php。我总是收到一条错误消息,提示缺少模板。确保有 edit.php 文件

    //$this->viewBuilder()->setTemplate('view'); //1.

    //$this->Crud->action()->setConfig('scaffold.view', 'view'); //2.

    //$this->render('view'); //3.
php cakephp cakephp-4.x
© www.soinside.com 2019 - 2024. All rights reserved.