在 Slim3 中渲染 Zend 表单

Rendering Zend Form in Slim3

我正在使用 Slim3 和 Zend Forms 2.6 (https://packagist.org/packages/zendframework/zend-form)。我正在尝试呈现表单,但出现错误:

Fatal error: Call to undefined method QuizApp\Forms\QuizForm::render() in /var/www/QuizApp/Routes/SurveyRoutes.php on line 25

我已将表单添加为 Slim3 中的一项服务:

$container['QuizForm'] = function() use ($app) {
    return new \QuizApp\Forms\QuizForm($app->SurveyServices);
};

这是我的表格:

class QuizForm extends \Zend\Form\Form
{ 
    private $survey_services;

    public function __construct(SurveyServices $survey_services, $name = null)
    {
        $this->survey_services = $survey_services;
        parent::__construct($name);
    }

    public function init()
    {
        /*
         * Set form method to POST
         */
        $this->setMethod('POST');

        /*
         * Add submit button to the form
         */   
        $this->add(array(
            'name' => 'submit',
            'type' => 'Submit',
            'attributes' => array(
                'value' => 'Get Quiz Results'
            ),
        ));
    }
}

我正在尝试在我的一条路线中呈现表单(最终我会将其传递给我的视图,但我正在测试):

$form = $this->QuizForm;

# Doesn't work
print $form;

# Doesn't work
print $form->render()

让我感到困惑的是文档说打印表格应该有效:http://framework.zend.com/manual/1.12/en/zend.form.quickstart.html#zend.form.quickstart.render

我没有使用 Zend 框架。我只使用了表单组件。

如何呈现表单?

你看错地方了。这是 Zend 1.12 版的文档。 您使用的是最新版本,请查看 here.

根据该文档资源,在渲染之前,您应该调用

$form->prepare();

另外,如果你想让渲染表单变得简单,你可能应该使用 Form View Helpers

看起来你没有正确的 DI 设置,如果你不能像这样转储表单... php var_dump($this->QuizForm); 那么该对象不在 this.

的上下文中

我怀疑您可能没有将它注入到您调用它的 class 中。但是您当前的问题是您需要将测验注入到您要渲染它的对象中。