在 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
由于 - Ash
答案 0 :(得分:5)
这是一个范围问题。当 Controller 呈现模板时,将功能放在控制器中可以正常工作。在您的情况下,表单正在呈现模板,您必须使用customise()告诉您的表单在使用{{3}}替换$TestFunction
时要使用的内容,例如返回时:
return $form->customise(array(
'TestFunction' => $this->TestFunction()
));
答案 1 :(得分:1)
PHP使用箭头代替点语法,就像其他编程语言一样。如果您尝试从php类的实例访问属性或函数,则使用箭头->
,如下所示:
$tmp = new Connectors_Controller();
echo $tmp->TestFunction();
现在,如果您尚未初始化班级的实例,则Scope Resolution Operator可以这样:
echo Connectors_Controller::TestFunction();
这将直接调用函数,而不是在对象上调用它。