建立表單

這是一個基本的示例表單,其中包含一個必需的文字欄位和一個提交按鈕,它們提交給自定義函式:

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