在 mysite/code/Connectors.php 中,我在 Page_Controller中使用自定义模板 创建了一个表单 strong> 这是代码:
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>
在我想从模板中的同一个 Controller 运行另一个函数之前,它工作正常。
通常我会简单地创建一个公共(public)函数并在模板中调用它——但这不起作用。
如何从自定义表单模板中访问函数?
我尝试了各种访问它的方法,例如 $Top.TestFunction
, $TestFunction()
和 $Parent.TestFunction
谢谢 - 灰
最佳答案
这是范围问题。当 Controller 呈现模板时,将函数放入您的 Controller 中效果很好。在你的例子中,Form 正在呈现模板,你必须告诉你的 Form 在它应该替换 $TestFunction
时使用什么,使用 customise() ,例如返回时:
return $form->customise(array(
'TestFunction' => $this->TestFunction()
));
关于php - Silverstripe 从自定义表单模板中访问函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32354981/