【问题标题】:October CMS: refreshing field values?十月 CMS:刷新字段值?
【发布时间】:2020-03-09 12:36:12
【问题描述】:

在我的插件中,当我编辑和保存项目时,某些字段值不会刷新。
例如,“updated_at”字段仍然显示旧的 DateTime 值,即使它已在数据库中更新。
如何刷新特定字段值?
我应该使用局部还是有其他方法可以做到这一点?

【问题讨论】:

    标签: octobercms


    【解决方案1】:

    在 FormController 中使用 AJAX 处理程序时,您可以使用以下方法更新表单中的单个字段:

    public function onYourAjaxHandler($recordID)
    {
        $model = MyModel::findOrFail($recordID);
        $model->fieldToUpdate = "new value";
        $this->initForm($model);
    
        $fieldMarkup = $this->formGetWidget()->renderField('fieldToUpdate', ['useContainer' => true]);
    
        return [
          '#field-id' => $fieldMarkup
        ];
    }
    

    如果需要替换字段容器,设置useContainer => false。如果需要保留容器,设置 useContainer => true。

    从 OctoberCMS v452 开始,现在可以直接使用 formRenderField() 方法,因为它添加了“选项”参数:

        $this->formRenderField('fieldToUpdate', ['useContainer'=>false])
    

    【讨论】:

    • 谢谢,我尝试在控制器中使用update_onSave() 函数,但出现此错误:Call to a member function renderField() on null 关于其他选项,我应该将$this->formRenderField() 代码行放在部分还是其他地方?
    • 您是否在控制器中使用 FormController 行为?
    • 是的,但是如果我将 formRenderField 代码放在我的 update_onSave() 函数中,我会收到一个错误:Call to a member function renderField() on null
    【解决方案2】:

    嗯,您需要将模型的 certain attributes/variables 设置为 achieve

    class YourModel extends Model
    {   
        // set this to true
        public $timestamps = true;   
    }
    

    $timestamps:如果trueautomatically 设置created_atupdated_at 字段。 (确保您的表具有完全相同的列名 created_atupdated_at

    检查参考:https://octobercms.com/docs/database/model#standard-properties

    如有任何疑问,请发表评论。

    【讨论】:

    • 谢谢,但我认为你误会了。保存时已正确设置 updated_at 字段,问题是该字段未刷新,我必须按浏览器的 F5 键才能显示新值。 here 讨论了这个问题,但解释很混乱,我不确定建议的解决方案是否正确。有什么想法吗?
    • 哦,我知道我跳过了it has been updated in the database 这一行,好的,让我看看是否有更好的解决方案
    猜你喜欢
    • 2017-07-27
    • 2016-06-07
    • 1970-01-01
    • 2019-02-03
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多