Php Silverstripe从自定义表单模板内部访问函数

Php Silverstripe从自定义表单模板内部访问函数,php,silverstripe,Php,Silverstripe,在mysite/code/Connectors.php中我在页面控制器中创建了一个带有自定义模板的表单,代码如下: class Connectors_Controller extends Page_Controller { private static $allowed_actions = array ( 'TestForm', 'TestFunction' ); public function TestFunction(){

mysite/code/Connectors.php中我在页面控制器中创建了一个带有自定义模板的表单,代码如下:

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>

$Field
$Actions.dataFieldByName(action\u doSubmit)
//我想要这个函数打印Hello World,但它没有
$TestFunction
在我想从模板中的同一个控制器运行另一个函数之前,这一切都很正常

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

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

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

谢谢
-与其他编程语言一样,PHP使用箭头而不是点语法。如果您试图从php类的实例访问属性或函数,请使用箭头
->
,如下所示:

$tmp = new Connectors_Controller();
echo $tmp->TestFunction();
echo Connectors_Controller::TestFunction();
现在,如果尚未初始化类的实例,可以这样:


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

这是一个范围问题。当控制器呈现模板时,将函数放入控制器中可以正常工作。在您的情况下,表单呈现模板时,您必须告诉表单在替换
$TestFunction
时使用什么,例如在返回模板时:

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

您好,谢谢您的回答,但我正在尝试从Silverstripe主题中访问该函数,以便执行更复杂的表单逻辑。是的,在我发布了答案后,我感觉它没有帮助。我对SS了解不多,它似乎使用了pythony风格的代码。对不起,我帮不上忙了。还有一个问题。是否有一种方法可以通过模板将参数返回到函数。像
$TestFunction(9)
或者
$TestFunction($Pos)
现在我只能运行这个函数,不能向它传递任何东西。谢谢,删除了分号。通常(在控制器中)您可以通过自定义将参数传递给它。。我不知道Customize是否可以接受闭包?值得一试……如果您真的需要向它传递参数,您可以使用扩展类扩展表单并将功能插入其中。大多数情况下,扩展比子类form好,而使用form类。