什么在 SilverStripe 表单中生成 .holder-required class

What generates the .holder-required class in SilverStripe forms

我正在 SilverStripe 中构建联系表单。

测试验证时,如果我将必填字段留空并点击提交,这些输入字段将添加 .holder-required class。即使我重新加载页面,它们也不会消失。 (实际上,错误消息 *** is required 也会在重新加载后保留在那里。我只是停止显示消息)。

我搜索了整个项目文件夹,但没有一个文件包含 holder-required

.holder-requiredclass从何而来?

你找不到 holder-required 的原因是因为它在技术上不存在于 SilverStripe 代码库中,它实际上是一个 class 由两个字符串连接在一起。

FormField中,有一个函数叫做"extraClass" which adds these classes to the field

下面是来自 FormField class:

的代码片段
public function extraClass() {
    $classes = array();

    $classes[] = $this->Type();

    if($this->extraClasses) {
        $classes = array_merge(
            $classes,
            array_values($this->extraClasses)
        );
    }

    if(!$this->Title()) {
        $classes[] = 'nolabel';
    }

    // Allow custom styling of any element in the container based on validation errors,
    // e.g. red borders on input tags.
    //
    // CSS class needs to be different from the one rendered through {@link FieldHolder()}.
    if($this->Message()) {
        $classes[] .= 'holder-' . $this->MessageType();
    }

    return implode(' ', $classes);
}

这告诉我们,对于针对某个字段出现的消息,它将附加 holder-{Whatever_Your_Message_Type_Is} 作为额外的 class。


为什么在页面重新加载后仍会设置 $this->Message() 的原因是错误信息实际上已保存到该表单的会话中。

下面是 a snippet from the Form class,它调用 FormField::setError(),在表单字段上设置消息 属性 的函数。

public function setupFormErrors() {
    $errorInfo = Session::get("FormInfo.{$this->FormName()}");

    if(isset($errorInfo['errors']) && is_array($errorInfo['errors'])) {
        foreach($errorInfo['errors'] as $error) {
            $field = $this->fields->dataFieldByName($error['fieldName']);

            if(!$field) {
                $errorInfo['message'] = $error['message'];
                $errorInfo['type'] = $error['messageType'];
            } else {
                $field->setError($error['message'], $error['messageType']);
            }
        }

        // load data in from previous submission upon error
        if(isset($errorInfo['data'])) $this->loadDataFrom($errorInfo['data']);
    }

    if(isset($errorInfo['message']) && isset($errorInfo['type'])) {
        $this->setMessage($errorInfo['message'], $errorInfo['type']);
    }

    return $this;
}

我浏览了 Form code, it should be clearing the errors after it is rendering the form. There are two functions part of the form class, clearMessage and resetValidation

通过forTemplate呈现表单模板时调用函数clearMessage。在整个 SilverStripe CMS 或框架代码库中,我没有看到 resetValidation 函数的任何用法。

如果在您的情况下消息未清除,您可能需要在代码中调用其中一个或另一个。