创建表单

这是一个基本的示例表单,其中包含一个必需的文本字段和一个提交按钮,它们提交给自定义函数:

class Page_Controller extends ContentController {

    private static $allowed_actions = array(
        'ExampleForm'
    );

    public function ExampleForm() {
        $fields = FieldList::create(
            TextField::create('Name', 'Your Name')
        );

        $actions = FieldList::create(
            FormAction::create('doExampleFormAction', 'Go')
        );

        $requiredFields = RequiredFields::create('Name');

        $form = Form::create(
            $this,
            'ExampleForm',
            $fields,
            $actions,
            $requiredFields
        );

        return $form;
    }

    public function doExampleFormAction($data, Form $form) {
        $form->sessionMessage('Hello '. $data['Name'], 'success');

        return $this->redirectBack();
    }
}

要显示此表单,我们将 $ExampleForm 添加到页面模板中:

$ExampleForm