表单提交后的silverstripe php表单验证(RequiredFields)

时间:2013-07-10 13:58:26

标签: forms content-management-system silverstripe

有没有办法在提交后使用必填字段进行表单验证,以便通过setSessionMessage()提供正确的错误消息? 如果我理解正确,如果未设置表单并且页面刚刚重新加载,则必填字段会阻止表单提交 - 因此不会调用提交函数。所以我的问题是,我是否必须手动检查提交功能以获取必需的字段才能获得自定义错误消息? 谢谢, 弗洛里安

2 个答案:

答案 0 :(得分:1)

SilverStripe表单比初看起来更复杂。

你是对的, 在提交之前检查验证器,并且仅当验证器返回true时才会调用表单操作。 (另请注意,表单操作永远不会作为URL公开,URL始终是自己的表单,然后调用表单操作。)

验证错误,设置错误(进入会话),表单重定向回来。然后从会话中获取错误。

silverstripe表单在构建时考虑了自定义验证。有一个名为Validator的类,扩展此类的所有内容都可用于验证表单。 (RequiredFields是Validator的子类)。 所以你可以用这种方式构建自己的验证器。 但是,如果您正在寻找常见的验证案例,那么您可能正在寻找令人敬畏的NetefxValidator模块:https://github.com/lx-berlin/NetefxValidator

它提供了许多验证表单的规则,例如:

  • 少于
  • 大于
  • text equals
  • text contains
  • 正则表达式
  • ...

它还可以将规则与andorxor合并(https://github.com/lx-berlin/NetefxValidator/tree/master/code/rules处的完整列表) 它甚至允许你指定一个自定义的PHP函数进行验证,如下所示:

# SilverStripe 3.x (but with some slight modifications it should also work in 2.x)
$fields = FieldList::create(array(
    TextField::create('myField', 'some label')
));
$actions = FieldList::create(array(
    FormAction::create('doSend', 'submit'),
));
$myValidationFunction = function ($data, $args) {
    if ($data['myField'] == 'zauberfisch is awesome' && $args['someOtherThing'] == 'yay') {
        // only allow this form to pass if the user acknowledges that zauberfisch is awesome
        return true;
    } else {
        return false;
    }
};
$additionalArguments = array('something' => 'ohai', 'someOtherThing' => 'yay');
$rule = NetefxValidatorRuleFUNCTION::create(
    $fieldName = 'myField',
    $errorMessage = 'to bad, you did not fill this field correctly',
    null,
    array($myValidationFunction, $additionalArguments)
);
$validator = NetefxValidator::create(array($rule));
$form = Form::create($this, $fields, $actions, $validator);

注意:Form::create()new Form()

基本相同

关于您想要在表单操作中设置错误消息的想法: BAD 的想法,您将遇到无数的麻烦尝试这样做。 验证者类存在是有原因的,不要试图滥用其他东西来做验证器应该做的事


编辑:更清楚地回答你的问题:

不,不可能设置自己的错误消息,您需要使用自定义验证器。

答案 1 :(得分:1)

虽然我可能做错了,但这就是我正在做我想你想做的事。

<?php
class Thing_Controller extends Page_Controller {

  /**
   * Controller action for the page with the form on it
   */
  public function page() {
      $this->ThingForm = $this->page_form();
      // Render using custom template templates/Layout/ThingFormPage.ss
      // which contains $ThingForm to output
      return $this->renderWith(array('ThingFormPage','Page'));
  }

  /**
   * Return form definition
   * Used both to display it and for validation
   */
  public function page_form() {
      $fields = new FieldList(
          new TextboxField('MyFormInput', 'Input Your Kerjiggers')
          );
      $actions = new FieldList($this->forwardButton());

      $required_fields = new RequiredFields(array('MyFormInput'));

      $form = new Form($this, 'Thing_Form', $fields, $actions, $required_fields);
      $form->setTemplate("Thing_Form");
      $form->setFormAction("Thing/page_save");
      $this->setFormMessageIfErrors($form);

      return $form;
  }

  /**
   * Validation, save and redirect
   */
  public function page_save() {
      $data = $this->request->postVars();

      $form = $this->page_form();
      $form->loadDataFrom($data);

      if ($form->validator->validate() === NULL) {
        // All good, proceed
        $this->redirect('another_action');
      } else {
        $errors = $form->validator->validate();
        foreach ($errors as $e) {
          $form->addErrorMessage($e['fieldName'], $e['message'], $e['messageType']);
        }
        $this->redirectBack();
      }
  }

  /**
   * If there are any errors on any RequiredFields, also set a form-level message at the top
   * so people know to scroll down and look for the specific errors.
   */
  protected function setFormMessageIfErrors($form) {
    $s = $this->getSession()->get_all();
    if (@$s['FormInfo']['Thing_Form']['errors']) {
      $form->setMessage("Please see the messages about your information below", 'info');
    }
  }
}