我正在 SilverStripe 中建立联系表格。

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

我搜索了整个项目文件夹,但没有一个文件包含 holder-required
.holder-required 类从何而来?

最佳答案

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

FormField 中,有一个名为 "extraClass" which adds these classes to the field 的函数。

下面是 FormField 类的代码片段:

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} 作为一个额外的类。
$this->Message() 在页面重新加载后仍会设置的原因是错误信息实际上已保存到该表单的 session 中。

下面是 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 进行了更多的浏览,它应该在呈现表单后清除错误。表单类有两个函数部分, clearMessage resetValidation
clearMessage 函数在通过 forTemplate 渲染表单模板时被调用。我没有看到在整个 SilverStripe CMS 或框架代码库中使用 resetValidation 函数。

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

关于php - 什么在 SilverStripe 表单中生成 .holder-required 类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32574997/

10-13 00:24