【发布时间】:2019-11-29 02:38:48
【问题描述】:
我正在尝试使用 Silverstripe 4 中的新 FormSchema 类,但我在提交表单的工作流程上遇到了困难。我已经能够返回架构和状态,但是在将表单提交回控制器时,我遇到了问题。下面是一些示例代码:
class TestController extends Controller {
private static $allowed_actions = [
'schema',
'TestForm'
];
public function schema(HTTPRequest $request) {
$schema = new FormSchema();
return json_encode($schema->getMultipartSchema(['schema', 'state', 'errors'], "FormID", $this->TestForm()));
}
public function TestForm() {
$fields = FieldList::create(
TextField::create('Name', 'Name'),
EmailField::create('Email', 'Email')
);
$actions = FieldList::create(
FormAction::create('doTestSubmit', 'Submit')
);
$required = RequiredFields::create(['Name', 'Email']);
return Form::create($this, 'TestForm', $fields, $actions, $required);
}
public function doTestSubmit($data, $form) {
return json_encode(array('response' => 'The form validated and was submitted.'));
}
}
所以在这种情况下,点击 /schema 会在 json 中返回 TestForm 模式,然后前端会呈现表单。提交表单会将数据发送回/TestForm 进行验证。如果提交有效,它将继续doTestSubmit 并返回响应。那太棒了!但是,如果提交无效,那么 TestForm 会尝试返回表单而不是带有验证消息的架构。
我首先考虑在TestForm() 中使用条件,例如if($this->request->isPOST()) 或if($form->validationResult()->isValid()),但这似乎不是处理它的正确方法。
任何输入或简单的代码示例都会很棒。
【问题讨论】:
标签: silverstripe silverstripe-4