自定义表单模板中的Silverstripe访问函数


Silverstripe accessing function from inside custom form template

mysite/code/Connectors.php我已经创建了一个表单自定义模板Page_Controller这里是代码:

class Connectors_Controller extends Page_Controller {
    private static $allowed_actions = array (
        'TestForm',
        'TestFunction'
    );
    public function TestFunction(){
        return 'Hello World!';
    }
    public function TestForm(){
        $fields = new FieldList(
            new TextField('Test', 'Test')
        );
        $actions = new FieldList(
            new FormAction('doSubmit', 'Submit')
        );
        $form = new Form($this, 'TestForm', $fields, $actions);
        $form->setTemplate('ContactForm');
        return $form;
    }
} 

我创建了一个包含页面themename/templates/Includes/ContactForm.ss

<form $FormAttributes id="contactform" action="$Link/Connectors" method="post" class="validateform AjaxForm">
    <% loop $Fields %>
        $Field 
    <% end_loop %>
    $Actions.dataFieldByName(action_doSubmit)
    // I want this function to print Hello World but it doesn't
    $TestFunction
</form>

这个工作正常,直到我想在模板中运行来自同一控制器的另一个函数。

通常我会简单地创建一个公共函数并在模板中调用它-但这不起作用。

如何从自定义表单模板中访问函数?

我已经尝试了各种方法访问它,如$Top.TestFunction, $TestFunction()$Parent.TestFunction

谢谢——灰

这是一个作用域问题。当 controller 渲染模板时,将函数放入控制器中可以正常工作。在你的情况下,表单正在渲染模板,你必须告诉你的表单使用什么,当它应该取代$TestFunction,使用自定义(),例如,当返回它:

return $form->customise(array(
    'TestFunction' => $this->TestFunction()
));

PHP使用箭头语法,而不是像其他编程语言那样使用点语法。如果你想从一个php类的实例中访问一个属性或函数,那么你可以像这样使用箭头->:

$tmp = new Connectors_Controller();
echo $tmp->TestFunction();

现在,如果你还没有初始化类的实例,你可以像这样解析作用域操作符:

echo Connectors_Controller::TestFunction();

这将直接调用函数,而不是在对象上调用。